Class: Csvdb::Row

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs, table, row) ⇒ Row

Returns a new instance of Row.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/csvdb/row.rb', line 5

def initialize(attrs, table, row)
  @table = table
  @row = row
  if attrs.is_a? Hash
    cols = @table.cols ; ary = []
    attrs.each do |key, val|
      ary[cols[key]] = convert(val)
      add_attr(key, convert(val)) if @table.cols.keys.include?(key)
    end
    super(ary)
  elsif attrs.is_a? Array
    super(attrs.map { |att| convert(att) })
    @table.cols.each { |col, idx| add_attr( col, convert(attrs[idx]) ) }
  else
    raise ParseError, "Cannot create a row out of a #{attrs.class}"
  end
end

Instance Attribute Details

#attrsObject

Returns the value of attribute attrs.



3
4
5
# File 'lib/csvdb/row.rb', line 3

def attrs
  @attrs
end

#rowObject

Returns the value of attribute row.



3
4
5
# File 'lib/csvdb/row.rb', line 3

def row
  @row
end

#tableObject

Returns the value of attribute table.



3
4
5
# File 'lib/csvdb/row.rb', line 3

def table
  @table
end

Instance Method Details

#deleteObject



32
33
34
35
# File 'lib/csvdb/row.rb', line 32

def delete
  @table.table[@row] = nil
  self
end

#to_hashObject



37
38
39
40
41
# File 'lib/csvdb/row.rb', line 37

def to_hash
  head = @table.cols.keys ; hash = {}
  self.map.with_index { |a, i| hash[head[i]] = a }
  hash
end

#update(attrs) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/csvdb/row.rb', line 23

def update(attrs)
  cols = @table.cols
  attrs.each do |att, new_val|
    @table.table[@row][cols[att.to_sym]] = new_val
    add_attr(att.to_sym, new_val) if @table.cols.keys.include?(att)
  end
  self
end