Class: Mafti

Inherits:
Object
  • Object
show all
Defined in:
lib/mafti.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(new_lines = []) ⇒ Mafti

Returns a new instance of Mafti.



7
8
9
10
11
12
# File 'lib/mafti.rb', line 7

def initialize(new_lines=[])
  @lines    = new_lines
  @data     = []
  @headers  = []
  parse
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



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

def data
  @data
end

#headersObject

Returns the value of attribute headers.



5
6
7
# File 'lib/mafti.rb', line 5

def headers
  @headers
end

#linesObject

Returns the value of attribute lines.



3
4
5
# File 'lib/mafti.rb', line 3

def lines
  @lines
end

Class Method Details

.open(filename) ⇒ Object



49
50
51
52
53
54
# File 'lib/mafti.rb', line 49

def self.open(filename)
  f = File.open(filename)
  lines = f.readlines
  f.close
  Mafti.new(lines)
end

Instance Method Details

#as_hashesObject



38
39
40
41
42
43
44
45
46
47
# File 'lib/mafti.rb', line 38

def as_hashes
  @data.inject([]) do |hashes, d|
    d = d.dup
    hashes << @headers.inject({}) do |hash, head|  
      hash[head] = d.shift 
      hash
    end
    hashes
  end
end

#parseObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mafti.rb', line 14

def parse
  @lines.each_with_index do |line, n|
    line = line.strip 
    case line
    
    when /^$/                  # '' (empty line)
      next
    when /^#.*$/               # '# Foo bar baz!' (a comment)
      next
    when /^-+$/                # '---------------------' (divider)
      next
    when /^(\|[^\|]*)*\|$/     # '| Foo   | Bar   | Baz   |' (valid data)
      new_data = parse_valid_line(line)
      unless headers_recorded?
        @headers = new_data
      else
        @data   << new_data
      end
    else
      raise "Line #{n} was invalid: #{line}"
    end
  end
end