Class: Tabl::Table

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

Defined Under Namespace

Classes: Format

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) {|_self| ... } ⇒ Table

Returns a new instance of Table.

Yields:

  • (_self)

Yield Parameters:

  • _self (Tabl::Table)

    the object that the method was called on



6
7
8
9
10
11
12
13
# File 'lib/tabl/table.rb', line 6

def initialize(args = {})
  @base_columns = {}
  add_base_columns(args[:base_columns] || {})
  @formats = {}
  @columns = {}
  self.columns=(args[:columns] || [])
  yield self if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/tabl/table.rb', line 53

def method_missing(name, *args)
  # Check columns first, creating an override if one doesn't exist already.
  column = @columns[name] || (@base_columns.include?(name) && @columns[name] = @base_columns[name].clone)
  if column
    yield column if block_given?
    return column
  end

  # Check formats next
  format = @formats[name]
  return format if format

  # Create a new format object
  format_base = Formats.send(name) || super
  @formats[name] = Format.new(name, self, format_base)
end

Instance Attribute Details

#columnsObject

Returns the value of attribute columns.



4
5
6
# File 'lib/tabl/table.rb', line 4

def columns
  @columns
end

#keysObject (readonly)

Returns the value of attribute keys.



3
4
5
# File 'lib/tabl/table.rb', line 3

def keys
  @keys
end

Instance Method Details

#add_base_columns(columns) ⇒ Object



15
16
17
18
19
# File 'lib/tabl/table.rb', line 15

def add_base_columns(columns)
  columns.each do |column|
    @base_columns[column.name] = column
  end
end

#base_columnsObject



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

def base_columns
  @base_columns.values
end

#column(key) ⇒ Object



49
50
51
# File 'lib/tabl/table.rb', line 49

def column(key)
  @columns[key] || @base_columns[key]
end

#labelsObject



37
38
39
# File 'lib/tabl/table.rb', line 37

def labels
  @keys.map { |key| column(key).label }
end

#to_csv(records) ⇒ Object



70
71
72
73
74
75
76
77
# File 'lib/tabl/table.rb', line 70

def to_csv(records)
  FasterCSV.generate do |csv|
    csv << labels
    records.each do |record|
      csv << values(record)
    end
  end
end

#value(key, record) ⇒ Object



45
46
47
# File 'lib/tabl/table.rb', line 45

def value(key, record)
  column(key).value(record)
end

#values(record) ⇒ Object



41
42
43
# File 'lib/tabl/table.rb', line 41

def values(record)
  @keys.map { |key| value(key, record) }
end