Class: Tabla

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

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, &block) ⇒ Tabla

Returns a new instance of Tabla.



26
27
28
29
30
# File 'lib/tabla.rb', line 26

def initialize(data, &block)
  @lines = data.split("\n")
  @fields = split @lines.shift
  @mapper = block
end

Class Attribute Details

.separatorObject

Returns the value of attribute separator.



7
8
9
# File 'lib/tabla.rb', line 7

def separator
  @separator
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



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

def data
  @data
end

#fieldsObject (readonly)

Returns the value of attribute fields.



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

def fields
  @fields
end

#mapperObject (readonly)

Returns the value of attribute mapper.



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

def mapper
  @mapper
end

Class Method Details

.dump(hashes) ⇒ Object



12
13
14
15
16
# File 'lib/tabla.rb', line 12

def self.dump(hashes)
  lines = [hashes.first.keys.join(" #{Tabla.separator} ")]
  lines += hashes.map { |i| i.values.join " #{Tabla.separator} " }
  lines.join("\n") << "\n"
end

.load(string) ⇒ Object



18
19
20
# File 'lib/tabla.rb', line 18

def self.load(string)
  new(string).parse
end

.load_file(path) ⇒ Object



22
23
24
# File 'lib/tabla.rb', line 22

def self.load_file(path)
  load File.read path
end

Instance Method Details

#each(&block) ⇒ Object



40
41
42
# File 'lib/tabla.rb', line 40

def each(&block)
  block ? data.each(&block) : data.each
end

#parseObject



32
33
34
35
36
37
38
# File 'lib/tabla.rb', line 32

def parse
  @data = @lines.map do |line|
    item = fields.zip(split(line)).to_h
    item = mapper.call(item) if mapper
    item
  end
end