class Csvdb::Row

Attributes

attrs[RW]
row[RW]
table[RW]

Public Class Methods

new(attrs, table, row) click to toggle source
Calls superclass method
# 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

Public Instance Methods

delete() click to toggle source
# File lib/csvdb/row.rb, line 32
def delete
  @table.table[@row] = nil
  self
end
to_hash() click to toggle source
# 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) click to toggle source
# 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

Private Instance Methods

add_attr(name, value) click to toggle source
# File lib/csvdb/row.rb, line 44
def add_attr(name, value)
  self.class.send(:attr_accessor, name)
  instance_variable_set("@#{name}", value)
end
convert(str) click to toggle source
# File lib/csvdb/row.rb, line 49
def convert(str)
  return str if str.class != String
  begin
    Integer(str)
  rescue ArgumentError
    begin
      Float(str)
    rescue ArgumentError
      return str
    end
  end
end