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.



136
137
138
139
140
# File 'lib/fasterer_csv.rb', line 136

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



201
202
203
# File 'lib/fasterer_csv.rb', line 201

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

Instance Attribute Details

#lineObject (readonly)

Returns the value of attribute line.



134
135
136
# File 'lib/fasterer_csv.rb', line 134

def line
  @line
end

Class Method Details

.to_key(key) ⇒ Object



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

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

Instance Method Details

#[](*is) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/fasterer_csv.rb', line 142

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



155
156
157
158
159
160
161
162
163
164
# File 'lib/fasterer_csv.rb', line 155

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



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

def headers
  @headers ||= @table.headers.dup
end

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

Returns:

  • (Boolean)


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

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

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



173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/fasterer_csv.rb', line 173

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



166
167
168
169
170
171
# File 'lib/fasterer_csv.rb', line 166

def pull(*columns)
  columns.map do |column|
    column = [nil] if column.nil?
    self[*column]
  end
end

#to_hashObject



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

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)


197
198
199
# File 'lib/fasterer_csv.rb', line 197

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