Class: ChainReactor::Parsers::Parser
- Inherits:
-
Object
- Object
- ChainReactor::Parsers::Parser
- Defined in:
- lib/chain-reactor/parsers/parser.rb
Overview
Base class for all concrete implementations of parsers.
Direct Known Subclasses
Instance Method Summary collapse
-
#do_parse(string) ⇒ Object
Parse the string, using an implmentation defined by child classes.
-
#initialize(logger) ⇒ Parser
constructor
Set up the parser with a logger object.
-
#parse(string, required_keys, keys_to_sym) ⇒ Object
Parse the string sent by the client.
Constructor Details
#initialize(logger) ⇒ Parser
Set up the parser with a logger object.
16 17 18 |
# File 'lib/chain-reactor/parsers/parser.rb', line 16 def initialize(logger) @log = logger end |
Instance Method Details
#do_parse(string) ⇒ Object
Parse the string, using an implmentation defined by child classes.
Should return a hash.
45 46 47 |
# File 'lib/chain-reactor/parsers/parser.rb', line 45 def do_parse(string) raise 'This method should implement a string to hash parser' end |
#parse(string, required_keys, keys_to_sym) ⇒ Object
Parse the string sent by the client.
Calls the do_parse() method which is defined by a subclass.
Required keys can be passed as an array, and a RequiredKeyError is raised if any of those keys don’t exist in the returned value from do_parse().
keys_to_sym converts all string keys to symbol keys, and is true by default.
30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/chain-reactor/parsers/parser.rb', line 30 def parse(string,required_keys,keys_to_sym) data = do_parse(string.strip) if keys_to_sym @log.debug { "Converting data keys #{data.keys} to symbols" } data = Hash[data.map { |k,v| [k.to_sym, v] }] end required_keys.each do |key| data.has_key? key or raise RequiredKeyError, "Required key '#{key}' is missing from data #{data}" end data end |