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) ⇒ Importer

Returns a new instance of Importer.



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

def initialize(database: Sequel.sqlite, table_name: "table", transformer: nil)
  @table_name = table_name
  @database   = database
  @transformer = transformer
  @table_created = false
end

Instance Attribute Details

#databaseObject (readonly)

Returns the value of attribute database.



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

def database
  @database
end

#table_nameObject (readonly)

Returns the value of attribute table_name.



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

def table_name
  @table_name
end

#transformerObject (readonly)

Returns the value of attribute transformer.



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

def transformer
  @transformer
end

Class Method Details

.class_supported?(clazz) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/jsonsql/importer.rb', line 42

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

Instance Method Details

#import(files) ⇒ Object



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

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

#import_jsonfile(filename) ⇒ Object



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

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



17
18
19
# File 'lib/jsonsql/importer.rb', line 17

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