Class: MiniXml

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(out) ⇒ MiniXml

Returns a new instance of MiniXml.



3
4
5
# File 'lib/mini_xml.rb', line 3

def initialize(out)
  @out = out
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(tagname, attributes = {}) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
# File 'lib/mini_xml.rb', line 70

def method_missing(tagname, attributes = {})
  @out << "<#{tagname}"
  @out << generate_attributes(attributes)
  @out << ">"
  if block_given?
    content = yield
    @out << content.to_s if content
    @out << "</#{tagname}>"
  end
  nil
end

Class Method Details

.generate(&block) ⇒ Object



7
8
9
10
11
# File 'lib/mini_xml.rb', line 7

def self.generate(&block)
  out = []
  MiniXml.new(out).instance_eval(&block)
  out.join("")
end

.xml_from_data(data = {}, fields = []) ⇒ Object



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
# File 'lib/mini_xml.rb', line 13

def self.xml_from_data(data = {}, fields = [])
  out = []
  xml_attributes = {}
  xml_attributes[:version] = (data[:xml_version] || '1.0')
  xml_attributes[:encoding] = (data[:encoding] || 'UTF-8')
  rss_version = data[:rss_version] || '2.0'
  title_str = data[:title] || 'RSS'
  description_str = data[:description] || ''
  link_str = data[:link] || ''
  generate do
    xml(xml_attributes)
    rss(version: rss_version) do
      channel do
        title {title_str}
        description {description_str}
        link {link_str}
        data[:data].each do |da|
          item do
            if da.is_a?(Hash)
              da.each do |k, v|
                next if fields.size > 0 && !fields.include?(k)
                p = proc {v}
                send(k, &p)
              end
            else
              raise 'fields argument can\'t empty!' if fields.empty?
              fields.each do |m|
                p = proc {da.send(m)}
                puts da.title
                send(m.to_s, &p)
              end
            end
            nil
          end
        end
        nil
      end
    end
  end
end

Instance Method Details

#comment(content) ⇒ Object



54
55
56
57
# File 'lib/mini_xml.rb', line 54

def comment(content)
  @out << "<!-- #{content} -->"
  nil
end

#generate_attributes(attributes_hash = {}) ⇒ Object



64
65
66
67
68
# File 'lib/mini_xml.rb', line 64

def generate_attributes(attributes_hash = {})
  attributes_str = ""
  attributes_hash.each {|key, val| attributes_str << " #{key}=\"#{val}\" "}
  attributes_str.rstrip
end

#xml(tagname, attributes = {version: '1.0', encoding: 'UTF-8'}) ⇒ Object



59
60
61
62
# File 'lib/mini_xml.rb', line 59

def xml(tagname, attributes = {version: '1.0', encoding: 'UTF-8'})
  @out << "<?xml#{generate_attributes(attributes)}?>"
  nil
end