Class: Midos::Reader

Inherits:
Base
  • Object
show all
Defined in:
lib/midos/reader.rb

Constant Summary collapse

DEFAULT_IO =
$stdin

Instance Attribute Summary collapse

Attributes inherited from Base

#auto_id, #fs, #io, #key, #le, #nl, #rs, #vs

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from Midos::Base

Instance Attribute Details

#recordsObject (readonly)

Returns the value of attribute records.



65
66
67
# File 'lib/midos/reader.rb', line 65

def records
  @records
end

Class Method Details

.parse(*args, &block) ⇒ Object



37
38
39
40
# File 'lib/midos/reader.rb', line 37

def parse(*args, &block)
  reader = new(args.extract_options!).parse(*args, &block)
  block ? reader : reader.records
end

.parse_file(*args, &block) ⇒ Object



42
43
44
# File 'lib/midos/reader.rb', line 42

def parse_file(*args, &block)
  file_method(:parse, 'r', *args, &block)
end

.transform(value, nl, vs, ovs = nil) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/midos/reader.rb', line 46

def transform(value, nl, vs, ovs = nil)
  rnl, rvs = replacements_for(*[nl, ovs].compact)

  value.gsub!(nl, "\n")
  value.gsub!(rnl, nl)

  !value.index(vs) ?
    replace!(value, rvs, ovs) || value :
    value.split(vs).each { |v| replace!(v, rvs, ovs) }
end

Instance Method Details

#parse(io = io(), &block) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/midos/reader.rb', line 77

def parse(io = io(), &block)
  unless block
    records, block = @records, amend_block { |id, record|
      records[id] = record
    }
  end

  id, record = nil, {}

  io.each { |line|
    line = line.chomp(le)

    if line == rs
      block[key ? id : auto_id.call, record]
      id, record = nil, {}
    else
      k, v = line.split(fs, 2)
      record[k] = k == key ? id = v : transform(v) if k && v
    end
  }

  self
end

#resetObject



67
68
69
70
# File 'lib/midos/reader.rb', line 67

def reset
  super
  @records = {}
end

#vs=(vs) ⇒ Object



72
73
74
75
# File 'lib/midos/reader.rb', line 72

def vs=(vs)
  @vs = vs.is_a?(Regexp) ? (@ovs = nil; vs) :
    %r{\s*#{Regexp.escape(@ovs = vs)}\s*}
end