Class: Jsonsql::Importer

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonsql/importer.rb

Constant Summary collapse

SEQUEL_SUPPORTED_CLASSES =
[Integer, String, Fixnum, Bignum, Float, BigDecimal, Date, DateTime, Time, Numeric, TrueClass, FalseClass]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(database: Sequel.sqlite, table_name: "table", transformer: nil, verbose: false) ⇒ Importer

Returns a new instance of Importer.



11
12
13
14
15
16
17
# File 'lib/jsonsql/importer.rb', line 11

def initialize(database: Sequel.sqlite, table_name: "table", transformer: nil, verbose: false)
  @table_name = table_name
  @database   = database
  @transformer = transformer
  @table_created = false
  @database.loggers << Logger.new($stdout) if verbose
end

Instance Attribute Details

#databaseObject (readonly)

Returns the value of attribute database.



9
10
11
# File 'lib/jsonsql/importer.rb', line 9

def database
  @database
end

#table_nameObject (readonly)

Returns the value of attribute table_name.



9
10
11
# File 'lib/jsonsql/importer.rb', line 9

def table_name
  @table_name
end

#transformerObject (readonly)

Returns the value of attribute transformer.



9
10
11
# File 'lib/jsonsql/importer.rb', line 9

def transformer
  @transformer
end

Class Method Details

.class_supported?(clazz) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/jsonsql/importer.rb', line 44

def self.class_supported?(clazz)
  SEQUEL_SUPPORTED_CLASSES.include?(clazz)
end

Instance Method Details

#import(files) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/jsonsql/importer.rb', line 23

def import(files)
  database.transaction do
    files.each do |filename|
      import_jsonfile(filename)
    end
  end
end

#import_jsonfile(filename) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/jsonsql/importer.rb', line 31

def import_jsonfile(filename)
  rowOrArrayOfRows = JSON.parse(open(filename).read)
  if rowOrArrayOfRows.is_a?(Array)
    rowOrArrayOfRows.each do |row|
      import_row(row)
    end
  elsif rowOrArrayOfRows.is_a?(Hash)
    import_row(rowOrArrayOfRows)
  else
    raise "Cannot import #{filename}, JSON file should contains Array or Hash."
  end
end

#tableObject



19
20
21
# File 'lib/jsonsql/importer.rb', line 19

def table
  @table ||= @database[table_name.to_sym]
end