Class: Charty::TableAdapters::HashAdapter

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/charty/table_adapters/hash_adapter.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, columns: nil) ⇒ HashAdapter

Returns a new instance of HashAdapter.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/charty/table_adapters/hash_adapter.rb', line 42

def initialize(data, columns: nil)
  case data
  when Hash
    @data = data
  when Array
    case data[0]
    when Numeric, String, Time, Date
      data = data.map {|x| [x] }
      @data = make_data_from_records(data, columns)
    when Hash
      # TODO
    when self.class.method(:array?)
      unsupported_data_format unless data.all?(&self.class.method(:array?))
      @data = make_data_from_records(data, columns)
    else
      unsupported_data_format
    end
  else
    unsupported_data_format
  end
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



64
65
66
# File 'lib/charty/table_adapters/hash_adapter.rb', line 64

def data
  @data
end

Class Method Details

.array?(data) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
39
40
# File 'lib/charty/table_adapters/hash_adapter.rb', line 30

def self.array?(data)
  case data
  when Array,
       ->(x) { defined?(Numo::NArray) && x.is_a?(Numo::NArray) },
       ->(x) { defined?(Daru::Vector) && x.is_a?(Daru::Vector) },
       ->(x) { defined?(NMatrix) && x.is_a?(NMatrix) }
    true
  else
    false
  end
end

.supported?(data) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/charty/table_adapters/hash_adapter.rb', line 12

def self.supported?(data)
  case data
  when []
    true
  when Array
    case data[0]
    when Numeric, String, Time, Date
      true
    when Hash
      data.all? {|el| el.is_a? Hash }
    when method(:array?)
      data.all?(&method(:array?))
    end
  when Hash
    true
  end
end

Instance Method Details

#[](row, column) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/charty/table_adapters/hash_adapter.rb', line 68

def [](row, column)
  if row
    @data[column][row]
  else
    @data[column]
  end
end

#eachObject



76
77
78
79
80
81
82
83
# File 'lib/charty/table_adapters/hash_adapter.rb', line 76

def each
  i, n = 0, shape[0]
  while i < n
    record = @data.map {|k, v| v[i] }
    yield record
    i += 1
  end
end