Class: WeakXml
- Inherits:
-
Object
- Object
- WeakXml
- Defined in:
- lib/weak_xml.rb,
lib/weak_xml/version.rb
Constant Summary collapse
- ATTRIBUTES_REGEXP =
Compiling regular expressions is expensive, specially if one uses variable parts. So, in order to achive the best performance, these should be compiled upfront without any “runtime dependencies”.
Regexp.compile(/\A<[^>\s]+\s+([^>]+)/m)
- CONTENT_REGEXP =
Regexp.compile(/.*?>(.*?)<[^>]+>\Z/m)
- VERSION =
"0.3.1"
Class Method Summary collapse
Instance Method Summary collapse
- #attr(key) ⇒ Object
- #content ⇒ Object
- #find(tag, options = nil) ⇒ Object
- #find_all(tag, options = nil) ⇒ Object
-
#initialize(xml, options = {}) ⇒ WeakXml
constructor
A new instance of WeakXml.
- #to_s ⇒ Object
Constructor Details
#initialize(xml, options = {}) ⇒ WeakXml
Returns a new instance of WeakXml.
39 40 41 42 43 |
# File 'lib/weak_xml.rb', line 39 def initialize(xml, = {}) = @tag = .delete(:tag) @xml = xml end |
Class Method Details
.find(tag, xml, options = {}) ⇒ Object
10 11 12 13 14 |
# File 'lib/weak_xml.rb', line 10 def self.find(tag, xml, = {}) if matched_string = xml[regex_factory(tag, )] self.new(matched_string, tag: tag) end end |
.find_all(tag, xml, options = {}) ⇒ Object
16 17 18 19 20 |
# File 'lib/weak_xml.rb', line 16 def self.find_all(tag, xml, = {}) xml.scan(regex_factory(tag, )).map! do |matched_string| self.new(matched_string, tag: tag) end end |
Instance Method Details
#attr(key) ⇒ Object
45 46 47 48 49 50 51 |
# File 'lib/weak_xml.rb', line 45 def attr(key) if match_data = @xml.match(ATTRIBUTES_REGEXP) if value_match_data = match_data.captures.first.match(/#{key}="(.+?)"/) value_match_data.captures.first end end end |
#content ⇒ Object
53 54 55 56 57 58 |
# File 'lib/weak_xml.rb', line 53 def content @content ||= if match_data = @xml.match(CONTENT_REGEXP) match_data.captures.first.tap(&:strip!) end end |
#find(tag, options = nil) ⇒ Object
60 61 62 |
# File 'lib/weak_xml.rb', line 60 def find(tag, = nil) self.class.find(tag, @xml, ( || )) end |
#find_all(tag, options = nil) ⇒ Object
64 65 66 |
# File 'lib/weak_xml.rb', line 64 def find_all(tag, = nil) self.class.find_all(tag, @xml, ( || )) end |
#to_s ⇒ Object
68 69 70 |
# File 'lib/weak_xml.rb', line 68 def to_s @xml end |