Class: Charty::Table

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, **kwargs) ⇒ Table

Returns a new instance of Table.



17
18
19
20
21
22
23
24
# File 'lib/charty/table.rb', line 17

def initialize(data, **kwargs)
  adapter_class = TableAdapters.find_adapter_class(data)
  if kwargs.empty?
    @adapter = adapter_class.new(data)
  else
    @adapter = adapter_class.new(data, **kwargs)
  end
end

Instance Attribute Details

#adapterObject (readonly)

Returns the value of attribute adapter.



26
27
28
# File 'lib/charty/table.rb', line 26

def adapter
  @adapter
end

Instance Method Details

#[](*args) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/charty/table.rb', line 34

def [](*args)
  n_args = args.length
  case n_args
  when 1
    row = nil
    column = args[0]
    @adapter[row, column]
  when 2
    row = args[0]
    column = args[1]
    @adapter[row, column]
  else
    message = "wrong number of arguments (given #{n_args}, expected 1..2)"
    raise ArgumentError, message
  end
end

#columnsObject



30
31
32
# File 'lib/charty/table.rb', line 30

def columns
  @column_accessor ||= ColumnAccessor.new(@adapter)
end

#eachObject



74
75
76
77
78
79
80
81
82
# File 'lib/charty/table.rb', line 74

def each
  return to_enum(__method__) unless block_given?
  data = to_a
  i, n = 0, data.size
  while i < n
    yield data[i]
    i += 1
  end
end

#to_a(x = nil, y = nil, z = nil) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/charty/table.rb', line 51

def to_a(x=nil, y=nil, z=nil)
  case
  when defined?(Daru::DataFrame) && table.kind_of?(Daru::DataFrame)
    table.map(&:to_a)
  when defined?(Numo::NArray) && table.kind_of?(Numo::NArray)
    table.to_a
  when defined?(NMatrix) && table.kind_of?(NMatrix)
    table.to_a
  when defined?(ActiveRecord::Relation) && table.kind_of?(ActiveRecord::Relation)
    if z && x && y
      [table.pluck(x), table.pluck(y), table.pluck(z)]
    elsif x && y
      [table.pluck(x), table.pluck(y)]
    else
      raise ArgumentError, "column_names is required to convert to_a from ActiveRecord::Relation"
    end
  when table.kind_of?(Array)
    table
  else
    raise ArgumentError, "unsupported object: #{table.inspect}"
  end
end