Class: FastererCSV::Row

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table, array, line = -1)) ⇒ Row

Returns a new instance of Row.



130
131
132
133
134
# File 'lib/fasterer_csv.rb', line 130

def initialize(table, array, line=-1)
  @table = table
  @line = line
  super(array)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



194
195
196
# File 'lib/fasterer_csv.rb', line 194

def method_missing(method, *args, &block)
  to_hash.send(method, *args, &block)
end

Instance Attribute Details

#lineObject (readonly)

Returns the value of attribute line.



128
129
130
# File 'lib/fasterer_csv.rb', line 128

def line
  @line
end

Class Method Details

.to_key(key) ⇒ Object



118
119
120
121
# File 'lib/fasterer_csv.rb', line 118

def to_key(key)
  key = "#{key}".downcase.gsub(/\s+/, '_')
  key.empty? ? :_ : key.to_sym
end

Instance Method Details

#[](*is) ⇒ Object



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

def [](*is)
  is.each do |i|
    val = if i.is_a? Fixnum
      super
    else
      found = headers.index(Row::to_key(i))
      found ? super(found) : nil
    end
    return val unless val.nil?
  end
  nil
end

#[]=(key, val) ⇒ Object



149
150
151
152
153
154
155
156
157
158
# File 'lib/fasterer_csv.rb', line 149

def []=(key, val)
  if key.is_a? Fixnum
    super
  else
    key = Row::to_key(key)
    headers << key unless headers.include? key
    found = headers.index(key)
    super(found, val)
  end
end

#headersObject Also known as: keys



124
125
126
# File 'lib/fasterer_csv.rb', line 124

def headers
  @table.headers
end

#key?(key) ⇒ Boolean Also known as: has_key?, member?, include?

Returns:

  • (Boolean)


186
187
188
# File 'lib/fasterer_csv.rb', line 186

def key?(key)
  keys.include?(Row.to_key(key))
end

#merge(row) ⇒ Object Also known as: merge!



166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/fasterer_csv.rb', line 166

def merge(row)
  if row.is_a? Row
    row.headers.each do |header|
      self[header] = row[header]
    end
  else
    row.each do |key, value|
      self[key] = value
    end
  end
  self
end

#pull(*columns) ⇒ Object



160
161
162
163
164
# File 'lib/fasterer_csv.rb', line 160

def pull(*columns)
  columns.map do |column|
    self[*column]
  end
end

#to_hashObject



179
180
181
182
183
184
# File 'lib/fasterer_csv.rb', line 179

def to_hash
  headers.inject({}) do |memo, h|
    memo[h] = self[h]
    memo
  end
end

#value?(value) ⇒ Boolean Also known as: has_value?

Returns:

  • (Boolean)


190
191
192
# File 'lib/fasterer_csv.rb', line 190

def value?(value)
  values.include?(value)
end