Class: CsvWizard::RowProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/csv_wizard/row_processor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, mapper, row, line_number, defaults: {}, before_import: nil, after_import: nil) ⇒ RowProcessor

Returns a new instance of RowProcessor.



5
6
7
8
9
10
11
12
13
14
# File 'lib/csv_wizard/row_processor.rb', line 5

def initialize(model, mapper, row, line_number, defaults: {}, before_import: nil, after_import: nil)
  @model = model
  @mapper = mapper
  @row = row
  @line_number = line_number
  @errors = []
  @defaults = defaults
  @before_import = before_import
  @after_import = after_import
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



3
4
5
# File 'lib/csv_wizard/row_processor.rb', line 3

def errors
  @errors
end

#line_numberObject (readonly)

Returns the value of attribute line_number.



3
4
5
# File 'lib/csv_wizard/row_processor.rb', line 3

def line_number
  @line_number
end

#mapperObject (readonly)

Returns the value of attribute mapper.



3
4
5
# File 'lib/csv_wizard/row_processor.rb', line 3

def mapper
  @mapper
end

#modelObject (readonly)

Returns the value of attribute model.



3
4
5
# File 'lib/csv_wizard/row_processor.rb', line 3

def model
  @model
end

#rowObject (readonly)

Returns the value of attribute row.



3
4
5
# File 'lib/csv_wizard/row_processor.rb', line 3

def row
  @row
end

Instance Method Details

#saveObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/csv_wizard/row_processor.rb', line 16

def save
  missing = mapper.required_columns.select { |col| row[col].nil? || row[col].strip.empty? }
  unless missing.empty?
    @errors = missing.map { |col| "#{col} is required" }
    return false
  end

  attrs = mapped_attributes
  attrs = @before_import.call(attrs) if @before_import

  record = model.new(attrs)
  if record.save
    @after_import.call(record) if @after_import
    true
  else
    @errors = record.errors.full_messages
    false
  end
rescue => e
  @errors = ["Exception: #{e.message}"]
  false
end