Class: EasyDom

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

Instance Method Summary collapse

Constructor Details

#initialize(obj = nil, debug: false, root: 'root') ⇒ EasyDom

Returns a new instance of EasyDom.



10
11
12
13
14
15
16
17
18
# File 'lib/easydom.rb', line 10

def initialize(obj=nil, debug: false, root: 'root')

  @debug = debug
  
  obj ||= "<#{root}/>"

  @e = obj.is_a?(String) ? FreeDom.new(obj).root : obj      

end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/easydom.rb', line 28

def method_missing(sym, *args, &block)

  puts "name: %s; args: %s" % [sym, args.inspect] if @debug

  if @e.respond_to? sym then
    
    puts 'attribute found' if @debug
    @e.method(sym).call(*args)
    
  elsif sym.to_s[-1] == '='
    
    # assumes the 1st attribute it finds is the attribute to be set
    
    puts '==' if @debug
    e = @e.element(sym.to_s[0..-2])
    
    if e.nil? then

      attribute = sym[0..-2]
      
      @e.instance_eval("def #{attribute}()
        attributes[:#{attribute}]
      end")
      
      @e.instance_eval("def #{sym}(val)
        attributes[:#{attribute}] = val
        val
      end")
      
      return @e.method(sym).call(args.first)
    end
    
    attr = e.attributes.keys.first.to_s        
    
    puts 'attribute: ' + attr.inspect if @debug
    
    e.method((attr + '=').to_sym).call(*args)
    
  else
    
    puts 'query element: ' + sym.to_s if @debug
    e = @e.element(sym.to_s)
    
    # if the element doesn't exist, create it
    e = @e.add FreeDom::Element.new(sym, attributes: {}) unless e
    
    EasyDom.new(e, debug: @debug) if e
    
  end

end

Instance Method Details

#==(v) ⇒ Object



20
21
22
# File 'lib/easydom.rb', line 20

def ==(v)
  @e.attributes.values.first.to_s == v
end

#to_sObject



24
25
26
# File 'lib/easydom.rb', line 24

def to_s()
  @e.attributes.values.first.to_s
end