Class: WeakXml

Inherits:
Object
  • Object
show all
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

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, options = {})
  @options = options
  @tag = options.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, options = {})
  if matched_string = xml[regex_factory(tag, options)]
    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, options = {})
  xml.scan(regex_factory(tag, options)).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

#contentObject



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, options = nil)
  self.class.find(tag, @xml, (options || @options))
end

#find_all(tag, options = nil) ⇒ Object



64
65
66
# File 'lib/weak_xml.rb', line 64

def find_all(tag, options = nil)
  self.class.find_all(tag, @xml, (options || @options))
end

#to_sObject



68
69
70
# File 'lib/weak_xml.rb', line 68

def to_s
  @xml
end