Class: Abaci::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/abaci/table.rb

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Table

Returns a new instance of Table.


3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/abaci/table.rb', line 3

def initialize(file)
  rows = CSV.read(file)
  columns = rows.shift
  @columns = []
  columns.each do |column|
    @columns << Column.new(column)
  end

  @rows = []
  rows.each do |row|
    values = {}
    @columns.each_with_index do |c, i|
      values[c.name] = c.cast(row[i].strip) if row[i].present?
    end
    @rows << Row.new(values)
  end
end

Instance Method Details

#collect(&block) ⇒ Object Also known as: map


29
30
31
# File 'lib/abaci/table.rb', line 29

def collect(&block)
  @rows.collect(&block)
end

#detect(&block) ⇒ Object


25
26
27
# File 'lib/abaci/table.rb', line 25

def detect(&block)
  @rows.detect(&block)
end

#each(&block) ⇒ Object


34
35
36
# File 'lib/abaci/table.rb', line 34

def each(&block)
  @rows.each(&block)
end

#select(&block) ⇒ Object


21
22
23
# File 'lib/abaci/table.rb', line 21

def select(&block)
  @rows.select(&block)
end

#where(properties) ⇒ Object

Filter rows with given properties


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/abaci/table.rb', line 39

def where(properties)
  @rows.select do |row|
    valid = true
    for name, value in properties
      property_value = row[name]
      if value.is_a?(Array)
        one_found = false
        for val in value
          if val.is_a?(Nomen::Item)
            one_found = true if property_value == val.name.to_sym
          else
            one_found = true if property_value == val
          end
        end
        valid = false unless one_found
      elsif value.is_a?(Nomen::Item)
        valid = false unless property_value == value.name.to_sym
      else
        valid = false unless property_value == value
      end
    end
    valid
  end
end