Class: MapFields::MappedFields

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, fields, mapping, ignore_first_row) ⇒ MappedFields

Returns a new instance of MappedFields.



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/map_fields.rb', line 110

def initialize(file, fields, mapping, ignore_first_row)
  @file = file
  @fields = fields
  @mapping = {}
  @ignore_first_row = ignore_first_row == '1'

  mapping.each do |k,v|
    unless v.to_i == 0
      #Numeric mapping
      @mapping[v.to_i - 1] = k.to_i - 1
      #Text mapping
      @mapping[fields[v.to_i-1]] = k.to_i - 1
      #Symbol mapping
      sym_key = fields[v.to_i-1].downcase.
                                  gsub(/[-\s\/]+/, '_').
                                  gsub(/[^a-zA-Z0-9_]+/, '').
                                  to_sym
      @mapping[sym_key] = k.to_i - 1
    end
  end
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



108
109
110
# File 'lib/map_fields.rb', line 108

def file
  @file
end

#ignore_first_rowObject (readonly)

Returns the value of attribute ignore_first_row.



108
109
110
# File 'lib/map_fields.rb', line 108

def ignore_first_row
  @ignore_first_row
end

#mappingObject (readonly)

Returns the value of attribute mapping.



108
109
110
# File 'lib/map_fields.rb', line 108

def mapping
  @mapping
end

Instance Method Details

#eachObject



136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/map_fields.rb', line 136

def each
  row_number = 1
  FasterCSV.foreach(@file) do |csv_row|
    unless row_number == 1 && @ignore_first_row
      row = {}
      @mapping.each do |k,v|
        row[k] = csv_row[v]
      end
      row.class.send(:define_method, :number) { row_number }
      yield(row)
    end
    row_number += 1
  end
end

#is_mapped?(field) ⇒ Boolean

Returns:

  • (Boolean)


132
133
134
# File 'lib/map_fields.rb', line 132

def is_mapped?(field)
  !@mapping[field].nil?
end