Class: HashMath::Table

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/hash_math/table.rb

Overview

The main data structure for a virtual table that can be treated as a key-value builder. Basically, it is a hash with a default ‘prototype’ assigned to it, which serves as the base record. Then, #add is called over and over passing in row_id, field_id, and value, which gives it enough information to pinpoint where to insert the data (memory-wise.) Imagine a two-dimensional table where X is the field_id axis and row is the Y axis. Since it is essentially backed by a hash, the row_id and field_id can be anything that implements #hash, #eql? and #== properly.

Defined Under Namespace

Classes: Row

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(record) ⇒ Table

Returns a new instance of Table.

Raises:

  • (ArgumentError)


28
29
30
31
32
33
34
35
# File 'lib/hash_math/table.rb', line 28

def initialize(record)
  raise ArgumentError, 'record is required' unless record

  @lookup = {}
  @record = record

  freeze
end

Instance Attribute Details

#lookupObject (readonly)

Returns the value of attribute lookup.



24
25
26
# File 'lib/hash_math/table.rb', line 24

def lookup
  @lookup
end

#recordObject (readonly)

Returns the value of attribute record.



24
25
26
# File 'lib/hash_math/table.rb', line 24

def record
  @record
end

Instance Method Details

#add(row_id, field_id, value) ⇒ Object



37
38
39
40
41
# File 'lib/hash_math/table.rb', line 37

def add(row_id, field_id, value)
  raise KeyOutOfBoundsError, "field_id: #{field_id} not allowed." unless key?(field_id)

  tap { set(row_id, field_id, value) }
end

#eachObject



43
44
45
46
47
48
49
# File 'lib/hash_math/table.rb', line 43

def each
  return enum_for(:each) unless block_given?

  lookup.map do |row_id, fields|
    Row.new(row_id, record.make!(fields)).tap { |row| yield(row) }
  end
end