Class: Uploadable::Processor

Inherits:
Object
  • Object
show all
Defined in:
lib/uploadable/processor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Processor

Returns a new instance of Processor.



6
7
8
9
10
# File 'lib/uploadable/processor.rb', line 6

def initialize options = {}
  self.model = options[:model]
  self.mandatory = options[:mandatory_fields]
  self.optional = options[:optional_fields]
end

Instance Attribute Details

#mandatoryObject

Returns the value of attribute mandatory.



5
6
7
# File 'lib/uploadable/processor.rb', line 5

def mandatory
  @mandatory
end

#modelObject

Returns the value of attribute model.



5
6
7
# File 'lib/uploadable/processor.rb', line 5

def model
  @model
end

#optionalObject

Returns the value of attribute optional.



5
6
7
# File 'lib/uploadable/processor.rb', line 5

def optional
  @optional
end

Instance Method Details

#transform_csv(csv_contents) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/uploadable/processor.rb', line 12

def transform_csv csv_contents
  records = []
  headers = ::CSV.parse_line(csv_contents, {:headers => true, :header_converters => :symbol}).to_hash.keys
  validate_headers headers
  extra_headers = headers - self.mandatory - self.optional
  ::CSV.parse(csv_contents, {:headers => true, :header_converters => :symbol}) do |row|
    record = row.to_hash.reject { |keys,v| extra_headers.include?keys }
    record.each do |attr_name, value|
      record[attr_name] = self.model.send("tranform_#{attr_name}_for_upload", value) if self.model.respond_to?("tranform_#{attr_name}_for_upload")
    end
    records << record
  end
  records
end