Module: NibblerMethods::InstanceMethods
- Defined in:
- lib/nibbler.rb
Instance Attribute Summary collapse
-
#doc ⇒ Object
readonly
Returns the value of attribute doc.
Instance Method Summary collapse
-
#initialize(doc) ⇒ Object
Initialize the parser with a document.
-
#parse ⇒ Object
Parse the document and save values returned by selectors.
-
#to_hash ⇒ Object
Dump the extracted data into a hash with symbolized keys.
Instance Attribute Details
#doc ⇒ Object (readonly)
Returns the value of attribute doc.
61 62 63 |
# File 'lib/nibbler.rb', line 61 def doc @doc end |
Instance Method Details
#initialize(doc) ⇒ Object
Initialize the parser with a document
64 65 66 67 68 |
# File 'lib/nibbler.rb', line 64 def initialize(doc) @doc = doc # initialize plural properties self.class.rules.each { |name, (s, k, plural)| send("#{name}=", []) if plural } end |
#parse ⇒ Object
Parse the document and save values returned by selectors
71 72 73 74 75 76 77 78 79 80 |
# File 'lib/nibbler.rb', line 71 def parse self.class.rules.each do |target, (selector, delegate, plural)| if plural send(target).concat @doc.search(selector).map { |i| parse_result(i, delegate) } else send("#{target}=", parse_result(@doc.at(selector), delegate)) end end self end |
#to_hash ⇒ Object
Dump the extracted data into a hash with symbolized keys
83 84 85 86 87 88 89 90 |
# File 'lib/nibbler.rb', line 83 def to_hash converter = lambda { |obj| obj.respond_to?(:to_hash) ? obj.to_hash : obj } self.class.rules.keys.inject({}) do |hash, name| value = send(name) hash[name.to_sym] = Array === value ? value.map(&converter) : converter[value] hash end end |