Class: StatefulParser
- Inherits:
-
Object
- Object
- StatefulParser
- Defined in:
- lib/stateful_parser.rb,
lib/stateful_parser/version.rb
Defined Under Namespace
Classes: Error
Constant Summary collapse
- VERSION =
"0.1.1"
Instance Method Summary collapse
-
#initialize(normalizer: nil) ⇒ StatefulParser
constructor
A new instance of StatefulParser.
- #parse(line) {|@state, line| ... } ⇒ Object
- #parse_string(string, &block) ⇒ Object
- #state(name, match, applies_to = [:none]) ⇒ Object
Constructor Details
#initialize(normalizer: nil) ⇒ StatefulParser
Returns a new instance of StatefulParser.
8 9 10 11 12 |
# File 'lib/stateful_parser.rb', line 8 def initialize(normalizer: nil) @state = :none @states = [] @normalizer = normalizer end |
Instance Method Details
#parse(line) {|@state, line| ... } ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/stateful_parser.rb', line 18 def parse(line) normalized_line = @normalizer ? @normalizer.call(line) : line matchers = @states.select { |s| s.last.include?(@state) || s.last.include?(:any) } new_state = nil matchers.each do |(name, match, _applies_to)| next unless normalized_line =~ match if new_state raise "multiple state transitions match: #{[new_state, name].inspect}" end new_state = name end @state = new_state if new_state yield @state, line end |
#parse_string(string, &block) ⇒ Object
34 35 36 37 38 |
# File 'lib/stateful_parser.rb', line 34 def parse_string(string, &block) string.each_line do |line| parse(line, &block) end end |
#state(name, match, applies_to = [:none]) ⇒ Object
14 15 16 |
# File 'lib/stateful_parser.rb', line 14 def state(name, match, applies_to = [:none]) @states << [name, match, applies_to] end |