Class: ServerSide::XML

Inherits:
Object show all
Defined in:
lib/serverside/xml.rb

Constant Summary collapse

TAG_LEFT_OPEN =
'<'.freeze
TAG_LEFT_CLOSE =
'</'.freeze
TAG_RIGHT =
'>'.freeze
INSTRUCT_LEFT =
'<?xml'.freeze
INSTRUCT_RIGHT =
'?>'.freeze
INSTRUCT_DEFAULT =
{:version => "1.0", :encoding => "UTF-8"}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(tag = nil, atts = nil, &block) ⇒ XML

Returns a new instance of XML.



44
45
46
47
48
49
# File 'lib/serverside/xml.rb', line 44

def initialize(tag = nil, atts = nil, &block)
  @doc = ''
  __open_tag(tag, atts) if tag
  block.call(self) if block
  __close_tag(tag) if tag
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/serverside/xml.rb', line 51

def method_missing(tag, *args, &block)
  if block
    __open_tag(tag, args.first)
    block.call(self)
    __close_tag(tag)
  else
    value, atts = args.pop, args.pop
    subtags, atts = atts, nil if atts.is_a?(Array)
    if subtags
      __open_tag(tag, atts)
      subtags.each {|k| __send__(k, value[k])}
      __close_tag(tag)
    else
      __open_tag(tag, atts)
      __value(value)
      __close_tag(tag)
    end
  end
  self
end

Instance Method Details

#__close_tag(tag) ⇒ Object



20
21
22
23
24
# File 'lib/serverside/xml.rb', line 20

def __close_tag(tag)
  @doc << TAG_LEFT_CLOSE
  @doc << tag.to_s
  @doc << TAG_RIGHT
end

#__fmt_atts(atts) ⇒ Object



39
40
41
# File 'lib/serverside/xml.rb', line 39

def __fmt_atts(atts)
  atts.inject('') {|m, i| m << " #{i[0]}=#{i[1].to_s.inspect}"}
end

#__instruct(arg) ⇒ Object



33
34
35
36
37
# File 'lib/serverside/xml.rb', line 33

def __instruct(arg)
  @doc << INSTRUCT_LEFT
  @doc << __fmt_atts(arg)
  @doc << INSTRUCT_RIGHT
end

#__open_tag(tag, atts) ⇒ Object



13
14
15
16
17
18
# File 'lib/serverside/xml.rb', line 13

def __open_tag(tag, atts)
  @doc << TAG_LEFT_OPEN
  @doc << tag.to_s
  @doc << __fmt_atts(atts) if atts
  @doc << TAG_RIGHT
end

#__value(value) ⇒ Object



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

def __value(value)
  @doc << value.to_s.html_escape
end

#instruct!(atts = nil) ⇒ Object



74
75
76
# File 'lib/serverside/xml.rb', line 74

def instruct!(atts = nil)
  __instruct(atts || INSTRUCT_DEFAULT)
end

#to_sObject Also known as: inspect



78
79
80
# File 'lib/serverside/xml.rb', line 78

def to_s
  @doc
end