Class: ScaffoldLogic::DataImport

Inherits:
Object
  • Object
show all
Defined in:
lib/scaffold_logic/data_import.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ DataImport

Instance Methods ===============================================================================



25
26
27
28
# File 'lib/scaffold_logic/data_import.rb', line 25

def initialize(file)
  @file = file
  raise 'You must specify a file' unless @file
end

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



7
8
9
# File 'lib/scaffold_logic/data_import.rb', line 7

def fields
  @fields
end

#fileObject (readonly)

Returns the value of attribute file.



7
8
9
# File 'lib/scaffold_logic/data_import.rb', line 7

def file
  @file
end

#row_mapObject (readonly)

Returns the value of attribute row_map.



7
8
9
# File 'lib/scaffold_logic/data_import.rb', line 7

def row_map
  @row_map
end

Class Method Details

.run(file) ⇒ Object

Class Methods ==================================================================================



10
11
12
# File 'lib/scaffold_logic/data_import.rb', line 10

def self.run(file)
  new(file).run
end

.save(upload) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/scaffold_logic/data_import.rb', line 14

def self.save(upload)
  # create file path
  _path = File.join('tmp', upload['datafile'].original_filename)

  # write file
   File.open(_path, 'wb') { |f| f.write(upload['datafile'].read) }

  self.run(_path)
end

Instance Method Details

#create_from_row(model) ⇒ Object



39
40
41
# File 'lib/scaffold_logic/data_import.rb', line 39

def create_from_row( model )
  model.create(row_map)
end

#initialize_row!Object



30
31
32
33
34
35
36
37
# File 'lib/scaffold_logic/data_import.rb', line 30

def initialize_row!
  unless @fields_initialized
    initialize_fields!
  else
    initialize_row_map!
    process_row
  end
end

#runObject



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/scaffold_logic/data_import.rb', line 43

def run
  @errors = []
  @row_index = 1

  (Object.const_defined?('FasterCSV') ? FasterCSV : CSV).foreach(file, :col_sep => "\t", :row_sep => :auto) do |arg|
    @row = arg
    initialize_row!
    @row_index += 1
  end

  @errors
end

#valid_row?Boolean

Returns:

  • (Boolean)


56
57
58
59
60
61
62
63
64
# File 'lib/scaffold_logic/data_import.rb', line 56

def valid_row?
  @missing_fields = []

  @required_fields.each do |field|
    @missing_fields << field if row_map[field].blank?
  end

  @missing_fields.empty?
end