Class: GenX::Builder

Inherits:
Blank
  • Object
show all
Defined in:
lib/genx4r/builder.rb

Instance Method Summary collapse

Constructor Details

#initialize(writer) ⇒ Builder

Returns a new instance of Builder.



13
14
15
16
17
18
19
20
21
22
# File 'lib/genx4r/builder.rb', line 13

def initialize(writer)
  @writer = writer

  @elements   = {}
  @attributes = {}
  @namespaces = {}

  @indent = 2
  @level  = 0
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



24
25
26
27
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
# File 'lib/genx4r/builder.rb', line 24

def method_missing(sym, *args, &block)
  text  = nil
  attrs = nil

  args.each do |arg|
    case arg
    when Hash
      attrs ||= {}
      attrs.merge!(arg)
    else
      text ||= ''
      text << arg.to_s
    end
  end

  _cache_element(sym)
  _cache_attrs(attrs) unless attrs.nil?

  if block
    raise ArgumentError, 'can\'t have both text and block' unless text.nil?
    _indent
    @writer.element(@elements[sym]) do
      _write_attrs(attrs) unless attrs.nil?
      _write_contents(block)
    end
    _newline
  else
    _indent
    @writer.element(@elements[sym]) do
      _write_attrs(attrs) unless attrs.nil?
      @writer.text(text)  unless text.nil?
    end
    _newline
  end
end

Instance Method Details

#_begin_doc(io) ⇒ Object



103
104
105
# File 'lib/genx4r/builder.rb', line 103

def _begin_doc(io)
  @writer.begin_document(io)
end

#_cache_attrs(attrs) ⇒ Object



77
78
79
80
81
82
83
# File 'lib/genx4r/builder.rb', line 77

def _cache_attrs(attrs)
  attrs.each_key do |attr|
    unless @attributes.has_key?(attr)
      @attributes[attr] = @writer.declare_attribute(attr.to_s)
    end
  end
end

#_cache_element(sym) ⇒ Object



85
86
87
88
89
# File 'lib/genx4r/builder.rb', line 85

def _cache_element(sym)
  unless @elements.has_key?(sym.to_s)
    @elements[sym] = @writer.declare_element(sym.to_s)
  end
end

#_end_docObject



107
108
109
# File 'lib/genx4r/builder.rb', line 107

def _end_doc
  @writer.end_document
end

#_indentObject



97
98
99
100
101
# File 'lib/genx4r/builder.rb', line 97

def _indent
  unless @indent == 0 || @level == 0
    @writer.text(" " * (@indent * @level))
  end
end

#_newlineObject



91
92
93
94
95
# File 'lib/genx4r/builder.rb', line 91

def _newline
  unless @indent == 0 || @level == 0
    @writer.text("\n")
  end
end

#_write_attrs(attrs) ⇒ Object



71
72
73
74
75
# File 'lib/genx4r/builder.rb', line 71

def _write_attrs(attrs)
  attrs.each_key do |attr|
    @writer.attribute(@attributes[attr], attrs[attr])
  end
end

#_write_contents(block) ⇒ Object



60
61
62
63
64
65
66
67
68
69
# File 'lib/genx4r/builder.rb', line 60

def _write_contents(block)
  begin
    @level += 1
    _newline
    block.call(self)
  ensure
    @level -= 1
    _indent
  end
end