Class: Tabledata::Tables

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/tabledata/tables.rb

Overview

This class represents a list of named tables.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tables) ⇒ Tables


37
38
39
# File 'lib/tabledata/tables.rb', line 37

def initialize(tables)
  @tables = tables
end

Class Method Details

.from_data(data, common_options = nil) ⇒ Object


11
12
13
14
15
16
17
18
# File 'lib/tabledata/tables.rb', line 11

def self.from_data(data, common_options=nil)
  common_options ||= {}
  tables           = Hash[data.map { |k,v|
    [k, v.is_a?(Table) ? v : Table.new(common_options.merge(name: name, data: v))]
  }]

  new(tables)
end

.from_file(path, options = nil) ⇒ Object


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/tabledata/tables.rb', line 20

def self.from_file(path, options=nil)
  options = options ? options.dup : {}
  options[:table_class] ||= Tabledata::Table
  options[:file_type]   ||= Detection.file_type_from_path(path)
  options[:name]        ||= File.basename(path).sub(/\.(?:csv|xlsx?)\z/, '')
  if options[:table_classes].is_a?(Array)
    options[:table_classes] = Hash[options[:table_classes].map { |table_class| [table_class.table_name, table_class] }]
  end

  case options[:file_type]
    when :csv then Parser.parse_csv(path, options)
    when :xls then Parser.tables_from_xls(path, options)
    when :xlsx then Parser.tables_from_xlsx(path, options)
    else raise InvalidFileType, "Unknown file format #{options[:file_type].inspect}"
  end
end

Instance Method Details

#[](key) ⇒ Object


49
50
51
# File 'lib/tabledata/tables.rb', line 49

def [](key)
  @tables[key]
end

#[]=(key, table) ⇒ Object


53
54
55
# File 'lib/tabledata/tables.rb', line 53

def []=(key, table)
  @tables[key] = table
end

#each(&block) ⇒ Object


41
42
43
# File 'lib/tabledata/tables.rb', line 41

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

#each_table(&block) ⇒ Object


45
46
47
# File 'lib/tabledata/tables.rb', line 45

def each_table(&block)
  @tables.each_value(&block)
end

#format(format_id, options = nil) ⇒ Object


66
67
68
# File 'lib/tabledata/tables.rb', line 66

def format(format_id, options=nil)
  Presenter.present(self, format_id, options)
end

#inspectObject


70
71
72
# File 'lib/tabledata/tables.rb', line 70

def inspect
  sprintf "#<%s %s>", self.class, @tables.inspect[1..-2]
end

#to_dataObject


57
58
59
# File 'lib/tabledata/tables.rb', line 57

def to_data
  Hash[@tables.map { |name, table| [name, table.to_nested_array] }]
end

#to_hashObject Also known as: to_h


61
62
63
# File 'lib/tabledata/tables.rb', line 61

def to_hash
  @tables.dup
end