Class: Csvdb::Table
- Inherits:
-
Object
- Object
- Csvdb::Table
- Defined in:
- lib/csvdb/table.rb
Instance Attribute Summary collapse
-
#cols ⇒ Object
Returns the value of attribute cols.
-
#table ⇒ Object
Returns the value of attribute table.
Instance Method Summary collapse
- #all ⇒ Object
- #count ⇒ Object
- #create(attrs) ⇒ Object
- #find(idx = nil) ⇒ Object
-
#initialize(opts = {}) ⇒ Table
constructor
A new instance of Table.
- #pluck(header) ⇒ Object
- #pretty ⇒ Object
- #where ⇒ Object
- #write(file = @file) ⇒ Object
Constructor Details
#initialize(opts = {}) ⇒ Table
Returns a new instance of Table.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/csvdb/table.rb', line 9 def initialize(opts = {}) if opts[:file] @file = opts[:file] table = CSV.read(@file) @cols = table[0].map.with_index {|head,idx| [head.to_sym,idx] }.to_h table.delete_at(0) elsif opts[:ary] table = opts[:ary] @cols = opts[:cols] else raise ParseError, 'No table or file to parse.' end @cols.each do |col, val| add_attr(col, val) end @table = [] table.each_with_index do |row, idx| @table[idx] = Row.new(row, self, idx) end end |
Instance Attribute Details
#cols ⇒ Object
Returns the value of attribute cols.
7 8 9 |
# File 'lib/csvdb/table.rb', line 7 def cols @cols end |
#table ⇒ Object
Returns the value of attribute table.
7 8 9 |
# File 'lib/csvdb/table.rb', line 7 def table @table end |
Instance Method Details
#all ⇒ Object
43 44 45 |
# File 'lib/csvdb/table.rb', line 43 def all @table end |
#count ⇒ Object
47 48 49 |
# File 'lib/csvdb/table.rb', line 47 def count @table.count end |
#create(attrs) ⇒ Object
51 52 53 54 55 56 57 |
# File 'lib/csvdb/table.rb', line 51 def create(attrs) new_row = [] attrs.each do |att, new_val| new_row[@cols[att]] = new_val end @table << Row.new(new_row, self, @table.length) end |
#find(idx = nil) ⇒ Object
63 64 65 66 67 68 69 70 71 |
# File 'lib/csvdb/table.rb', line 63 def find(idx = nil) if block_given? @table.select { |row| yield(row) }.first elsif idx @table[idx] else raise ArgumentError, 'Must pass either an index or a block.' end end |
#pluck(header) ⇒ Object
73 74 75 76 77 78 79 80 |
# File 'lib/csvdb/table.rb', line 73 def pluck(header) col = @cols[header.to_sym] ; vals = [] raise SearchError, "Column #{header} does not exist." unless col @table.each do |row| vals << row[col] end vals end |
#pretty ⇒ Object
82 83 84 85 |
# File 'lib/csvdb/table.rb', line 82 def pretty table = Terminal::Table.new headings: @cols.keys, rows: @table puts table end |
#where ⇒ Object
59 60 61 |
# File 'lib/csvdb/table.rb', line 59 def where Table.new(ary: @table.select { |row| yield(row) }, cols: self.cols) end |
#write(file = @file) ⇒ Object
34 35 36 37 38 39 40 41 |
# File 'lib/csvdb/table.rb', line 34 def write(file = @file) CSV.open(file, 'wb') do |csv| csv << @cols.keys @table.each do |row| csv << row end end end |