Class: Ghaki::Match::Parser::Base
- Inherits:
-
Object
- Object
- Ghaki::Match::Parser::Base
- Defined in:
- lib/ghaki/match/parser/base.rb
Overview
Matches against paired regular expressions and returned values.
Direct Known Subclasses
Instance Attribute Summary collapse
-
#default_value ⇒ Object
Returns the value of attribute default_value.
-
#match_lookup ⇒ Object
Returns the value of attribute match_lookup.
Instance Method Summary collapse
-
#add_words(pairs) ⇒ Object
Add simple words with return values to match pairs.
-
#initialize(opts = {}) ⇒ Base
constructor
A new instance of Base.
-
#match_lines(lines, opts = {}) ⇒ Object
Matches lines against regexp keys returning paired value.
-
#match_text(text, opts = {}) ⇒ Object
Matches string against regexp keys returning paired value.
Constructor Details
#initialize(opts = {}) ⇒ Base
Returns a new instance of Base.
10 11 12 13 14 |
# File 'lib/ghaki/match/parser/base.rb', line 10 def initialize opts={} @match_lookup = opts[:match_lookup] || {} @default_value = opts[:default_value] add_words( opts[:match_words] ) if opts.has_key?(:match_words) end |
Instance Attribute Details
#default_value ⇒ Object
Returns the value of attribute default_value.
8 9 10 |
# File 'lib/ghaki/match/parser/base.rb', line 8 def default_value @default_value end |
#match_lookup ⇒ Object
Returns the value of attribute match_lookup.
8 9 10 |
# File 'lib/ghaki/match/parser/base.rb', line 8 def match_lookup @match_lookup end |
Instance Method Details
#add_words(pairs) ⇒ Object
Add simple words with return values to match pairs.
-
Keys are return values, values are words to turn into regexps.
Given:
add_words :up => %w{ ON UP }, :down => %w{ DOWN OFF }
This will match against ‘ON’ and ‘UP’ and return :up and match against ‘DOWN’ and ‘OFF’ and return :down
25 26 27 28 29 30 31 |
# File 'lib/ghaki/match/parser/base.rb', line 25 def add_words pairs pairs.each_pair do |val,keyz| keyz.each do |key| @match_lookup[ %r{\A#{key}\z}i ] = val end end end |
#match_lines(lines, opts = {}) ⇒ Object
Matches lines against regexp keys returning paired value.
-
Yields on not found or returns default value.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/ghaki/match/parser/base.rb', line 35 def match_lines lines, opts={} @match_lookup.each_pair do |rx_curr,ret_val| lines.each do |text| return ret_val if text =~ rx_curr end end if block_given? yield elsif opts.has_key?(:default_value) opts[:default_value] else @default_value end end |
#match_text(text, opts = {}) ⇒ Object
Matches string against regexp keys returning paired value.
-
Yields on not found or returns default value.
52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/ghaki/match/parser/base.rb', line 52 def match_text text, opts={} @match_lookup.each_pair do |rx_curr,ret_val| return ret_val if text =~ rx_curr end if block_given? yield elsif opts.has_key?(:default_value) opts[:default_value] else @default_value end end |