Class: Relief::Element

Inherits:
Object
  • Object
show all
Defined in:
lib/relief/element.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options, &block) ⇒ Element

Returns a new instance of Element.



5
6
7
8
9
10
11
# File 'lib/relief/element.rb', line 5

def initialize(name, options, &block)
  @name = name
  @options = options
  @children = {}

  instance_eval(&block) if block_given?
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



3
4
5
# File 'lib/relief/element.rb', line 3

def children
  @children
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/relief/element.rb', line 3

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/relief/element.rb', line 3

def options
  @options
end

Instance Method Details

#attribute(name, options = {}, &block) ⇒ Object



45
46
47
# File 'lib/relief/element.rb', line 45

def attribute(name, options={}, &block)
  element(name, options.merge(:attribute => true), &block)
end

#element(name, options = {}, &block) ⇒ Object



35
36
37
38
39
# File 'lib/relief/element.rb', line 35

def element(name, options={}, &block)
  options[:xpath] ||= name if name =~ %r([/.])
  name = options[:as].to_sym if options.has_key?(:as)
  @children[name] ||= self.class.new(name, options, &block)
end

#elements(name, options = {}, &block) ⇒ Object



41
42
43
# File 'lib/relief/element.rb', line 41

def elements(name, options={}, &block)
  element(name, options.merge(:collection => true), &block)
end

#parse(document) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/relief/element.rb', line 13

def parse(document)
  @children.inject({}) do |values, child|
    name, element = child

    values[name] = begin
      target = (document / element.xpath)

      parse_node = lambda { |target|
        element.children.any? ? element.parse(target) : target.to_s
      }

      if element.options[:collection]
        target.collect { |child| parse_node.call(child) }
      else
        parse_node.call(target)
      end
    end

    values
  end
end

#xpathObject



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/relief/element.rb', line 49

def xpath
  if options.has_key?(:xpath)
    options[:xpath]
  elsif @children.empty?
    attribute = @options[:attribute]
    attribute = name if attribute == true
    !attribute ? "#{name}/text()" : "@#{attribute}"
  else
    name.to_s
  end
end