Class: RexleBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/rexle-builder.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj = nil, debug: false) ⇒ RexleBuilder

Returns a new instance of RexleBuilder.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rexle-builder.rb', line 23

def initialize(obj=nil, debug: false)
  
  @debug = debug
  @a = []
  @current_a = @a
  @namespace = nil
  
  if obj.is_a? Hash then
    
    key = obj.keys.first      
    
    if obj.length > 1 or obj[key].is_a?(Array) or obj[key].is_a?(String) then
      self.root { buildx obj} 
    else
      self.send(key.to_sym) {buildx obj[key]}
    end

  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object



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
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/rexle-builder.rb', line 52

def method_missing(sym, *args)
  
  args << '' if args.last.is_a? Hash 
  value, attributes = args.reverse
  
  if value =~ /^<.*>$/ then
    
    a = [
      sym.to_s, 
      attributes, 
      *Rexle.new("<root>%s</root>" % value).to_a[2..-1]
    ]
    
  end
  
  if @debug then
    puts 'sym: ' + sym.inspect
    puts 'args: ' + args.inspect
  end
  
  # reserved keywords are masked with ._ e.g. ._method_missing
  a ||= [sym.to_s.sub(/^(?:\._|_)/,'').sub(/^cdata!$/,'![')\
       .sub(/^comment!$/, '!-'), attributes || {}, value || '']

  if @namespace then 
    a.first.prepend(@namespace + ':')
    @namespace = nil 
  end

  @current_a << a
  
  if block_given? then
    
    prev_a = @current_a
    @current_a = a
    
    r = yield()     
    
    @current_a.concat r if r.class == RexleArray
    @current_a = prev_a      
    
  end
  
  @a.first
end

Class Method Details

.build(debug: false) {|self.new(debug: debug)| ... } ⇒ Object

Yields:

  • (self.new(debug: debug))


17
18
19
20
21
# File 'lib/rexle-builder.rb', line 17

def self.build(debug: false)

  yield(self.new(debug: debug))

end

Instance Method Details

#[](s) ⇒ Object



43
44
45
46
# File 'lib/rexle-builder.rb', line 43

def [](s)
  @namespace = s
  self
end

#to_aObject



48
49
50
# File 'lib/rexle-builder.rb', line 48

def to_a
  @a.first
end