Class: Object

Inherits:
BasicObject
Defined in:
lib/xmlize/object.rb

Instance Method Summary collapse

Instance Method Details

#tokens_for_xmlize(tag, attributes = {}) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/xmlize/object.rb', line 58

def tokens_for_xmlize(tag, attributes = {})
  tokens = [['START', tag]]
  tokens.concat attributes.map { |k, v| ['ATTR', k, v] }
  tokens << ['TEXT', to_s]
  tokens << ['END', tag]
  tokens
end

#xmlize(tag, attributes = {}, options = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
# File 'lib/xmlize/object.rb', line 4

def xmlize(tag, attributes = {}, options = {})
  options[:add_xml_decl] = options.has_key?(:add_xml_decl) ? true                 : options[:add_xml_decl]
  options[:version]      = options.has_key?(:version)      ? options[:version]    : '1.0'
  options[:encoding]     = options.has_key?(:encoding)     ? options[:encoding]   : 'utf-8'
  options[:standalone]   = options.has_key?(:standalone)   ? options[:standalone] : nil
  options[:rails]        = options.has_key?(:rails)        ? options[:rails]      : false
  chunks = []
  state = 'STARTDOC'
  tokens_for_xmlize(tag, attributes).each do |token|
    case token.first
      when 'START'
        if state == 'STARTDOC'
          if (options[:add_xml_decl])
            chunks.push("<?xml version=\"#{options[:version]}\" encoding=\"#{options[:encoding]}\"?>")
          end
        end
        chunks.push(">") if state == 'IN_START'
        name = token[1]
        name = name.gsub(/_/, '-') if options[:rails]
        chunks.push "<#{name}"
        state = 'IN_START'
        
      when 'ATTR'
        value = token[2].gsub(/\"/, '&quot;')
        chunks.push " #{token[1]}=\"#{value}\""
        state = 'IN_START'
        
      when 'TEXT'
        chunks.push(">") if state == 'IN_START'
        text = token[1]
        [
          [/&/, '&amp;'],
          [/\"/, "&quot;"],
          [/>/, "&gt;"],
          [/</, "&lt;"]
        ].each { |e| text.gsub! e[0], e[1] }
        chunks.push(text)
        state = 'IN_TEXT'
        
      when 'END'
        if (state == 'IN_START')
          chunks.push(' />')
        else
          name = token[1]
          name = name.gsub /_/, '-' if (options[:rails])
          chunks.push("</#{name}>")
        end
        state = 'IN_END'
        
    end
  end
  chunks.join('')
end