File: xml.rb

package info (click to toggle)
ruby-representable 3.0.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 896 kB
  • sloc: ruby: 6,432; makefile: 3
file content (77 lines) | stat: -rw-r--r-- 1,867 bytes parent folder | download | duplicates (3)
1
2
3
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
require 'representable'

begin
  require 'nokogiri'
rescue LoadError => _
  abort "Missing dependency 'nokogiri' for Representable::XML. See dependencies section in README.md for details."
end

module Representable
  module XML
    def self.included(base)
      base.class_eval do
        include Representable
        extend ClassMethods
        self.representation_wrap = true # let representable compute it.
        register_feature Representable::XML
      end
    end


    module ClassMethods
      def remove_namespaces!
        representable_attrs.options[:remove_namespaces] = true
      end

      def format_engine
        Representable::XML
      end

      def collection_representer_class
        Collection
      end
    end

    def from_xml(doc, *args)
      node = parse_xml(doc, *args)

      from_node(node, *args)
    end

    def from_node(node, options={})
      update_properties_from(node, options, Binding)
    end

    # Returns a Nokogiri::XML object representing this object.
    def to_node(options={})
      options[:doc] = Nokogiri::XML::Document.new # DISCUSS: why do we need a fresh Document here?
      root_tag = options[:wrap] || representation_wrap(options)

      create_representation_with(Node(options[:doc], root_tag.to_s), options, Binding)
    end

    def to_xml(*args)
      to_node(*args).to_s
    end

    alias_method :render, :to_xml
    alias_method :parse, :from_xml

  private
    def remove_namespaces?
      # TODO: make local Config easily extendable so you get Config#remove_ns? etc.
      representable_attrs.options[:remove_namespaces]
    end

    def parse_xml(doc, *args)
      node = Nokogiri::XML(doc)

      node.remove_namespaces! if remove_namespaces?
      node.root
    end
  end
end

require "representable/xml/binding"
require "representable/xml/collection"
require "representable/xml/namespace"