Class: EasyDom

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of EasyDom.



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

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



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
79
80
81
82
83
84
# File 'lib/easydom.rb', line 34

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 Attribute Details

#eObject (readonly)

Returns the value of attribute e.



10
11
12
# File 'lib/easydom.rb', line 10

def e
  @e
end

Instance Method Details

#==(v) ⇒ Object



22
23
24
# File 'lib/easydom.rb', line 22

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

#to_sObject



26
27
28
# File 'lib/easydom.rb', line 26

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

#to_slimlObject



30
31
32
# File 'lib/easydom.rb', line 30

def to_sliml()
  @e.to_sliml()
end