Module: CSVMachine::ClassMethods

Defined in:
lib/csv-machine.rb

Overview

TODO: def self.map(klass, &block) end

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#csv_fieldsObject (readonly)

Returns the value of attribute csv_fields.



14
15
16
# File 'lib/csv-machine.rb', line 14

def csv_fields
  @csv_fields
end

#csv_optionsObject (readonly)

Returns the value of attribute csv_options.



15
16
17
# File 'lib/csv-machine.rb', line 15

def csv_options
  @csv_options
end

Instance Method Details

#create_attribute(name) ⇒ Object



54
55
56
57
# File 'lib/csv-machine.rb', line 54

def create_attribute(name)
  attr_reader name unless method_defined?(name)
  attr_writer name unless method_defined?(:"#{name}=")
end

#field(name, options = {}) ⇒ Object

Parameters:

  • name (Symbol, #to_sym)
  • options (Hash) (defaults to: {})


33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/csv-machine.rb', line 33

def field(name, options={})
  #options.clone do |hash|
    #hash[(key.to_sym rescue key) || key] = options.delete(key)
  #end
  
  options[:column] ||= begin
    csv_fields.empty? ? 0 : ( csv_fields.values.last.options[:column] + 1 )
  end

  _field = Field.new(name, options)
  create_attribute(_field.name)
  csv_fields[_field.name] = _field
end

#from_csv(row) ⇒ Object

Parameters:

  • row (Array)

    Parsed csv row



48
49
50
51
52
# File 'lib/csv-machine.rb', line 48

def from_csv(row)
  new.tap do |obj|
    csv_fields.each { |n, f| obj.__send__(:"#{n}=", row[f.column]) }
  end
end

#parse(data) ⇒ Object



59
60
61
# File 'lib/csv-machine.rb', line 59

def parse(data)
  CSV.new(data, csv_options).collect { |row| from_csv(row) }
end

#set_csv_option(name, value) ⇒ Object

Parameters:

  • name (Symbol)
  • []

    value



27
28
29
# File 'lib/csv-machine.rb', line 27

def set_csv_option(name, value)
  raise "Unknown csv option `#{name}'" unless csv_options.key?(name)
end