Class: Tokamak::Builder::Xml

Inherits:
Base
  • Object
show all
Defined in:
lib/tokamak/builder/xml.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

build, builder_for, collection_helper_default_options, generic_helper, global_media_types, helper, media_types, member_helper_default_options

Constructor Details

#initialize(obj, options = {}) ⇒ Xml

Returns a new instance of Xml.



9
10
11
12
13
14
15
# File 'lib/tokamak/builder/xml.rb', line 9

def initialize(obj, options = {})
  initialize_library
  @raw = Nokogiri::XML::Document.new
  @obj = obj
  @parent = @raw.create_element(options[:root] || "root")
  @parent.parent = @raw
end

Instance Attribute Details

#rawObject (readonly)

Returns the value of attribute raw.



7
8
9
# File 'lib/tokamak/builder/xml.rb', line 7

def raw
  @raw
end

Instance Method Details

#initialize_libraryObject



17
18
19
20
# File 'lib/tokamak/builder/xml.rb', line 17

def initialize_library
  return if defined?(::Nokogiri)
  require "nokogiri"
end

#insert_value(name, prefix, *args, &block) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/tokamak/builder/xml.rb', line 52

def insert_value(name, prefix, *args, &block)
  node = create_element(name.to_s, prefix, *args)
  node.parent = @parent
  if block_given?
    @parent = node
    block.call
    @parent = node.parent
  end
end


45
46
47
48
49
50
# File 'lib/tokamak/builder/xml.rb', line 45

def link(relationship, uri, options = {})
  options["rel"] = relationship.to_s
  options["href"] = uri
  options["type"] ||= options[:type] || "application/xml"
  insert_value("link", nil, options)
end

#members(options = {}, &block) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/tokamak/builder/xml.rb', line 22

def members(options = {}, &block)
  collection = options[:collection] || @obj
  raise Tokamak::BuilderError.new("Members method require a collection to execute") unless collection.respond_to?(:each)
  collection.each do |member|
    member_root = @raw.create_element(options[:root] || "member")
    member_root.parent = @parent
    @parent = member_root
    block.call(self, member)
    @parent = member_root.parent
  end
end

#representationObject



62
63
64
# File 'lib/tokamak/builder/xml.rb', line 62

def representation
  @raw.to_xml
end

#values(options = {}) {|Values.new(self)| ... } ⇒ Object

Yields:



34
35
36
37
38
39
40
41
42
43
# File 'lib/tokamak/builder/xml.rb', line 34

def values(options = {}, &block)
  options.each do |key,value|
    attr = key.to_s
    if attr =~ /^xmlns(:\w+)?$/
      ns = attr.split(":", 2)[1]
      @parent.add_namespace_definition(ns, value)
    end
  end
  yield Values.new(self)
end