Module: Utils

Included in:
DslRuntime, Extractor2, RootCleanroom, RoxmlBuilder
Defined in:
lib/roundtrip_xml/utils.rb

Defined Under Namespace

Classes: UndefinedParam

Constant Summary collapse

VAR_SUFIX =
'_v'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



19
20
21
22
23
# File 'lib/roundtrip_xml/utils.rb', line 19

def self.included(base)
  unless base.const_defined?(:VAR_SUFIX)
    base.const_set :VAR_SUFIX, Utils::VAR_SUFIX
  end
end

Instance Method Details

#name_to_sym(name, lower_case = false) ⇒ Object



75
76
77
# File 'lib/roundtrip_xml/utils.rb', line 75

def name_to_sym(name, lower_case = false)
  name_to_sym_helper(name, lower_case)
end

#new_roxml_class(name, parent = Object, &block) ⇒ Object



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
# File 'lib/roundtrip_xml/utils.rb', line 24

def new_roxml_class(name, parent = Object, &block)
  Class.new(parent) do
    include ROXML
    include PlainAccessors
    xml_convention :dasherize
    xml_name name

    # by default a ROXML class isn't a sub class
    def self.subclass?
      @is_subclass || false
    end
    def attributes
      self.class.roxml_attrs
    end

    def self.class_name
      self.tag_name.is_a?(Symbol) ? self.tag_name : name_to_sym_helper(self.tag_name)
    end

    def to_hash
      attributes.inject({}) do |hash, a|
        value = a.to_ref(self).to_xml(self)
        value = value.to_hash if value.respond_to? :to_hash

        hash[a.accessor] = value
        hash['__class'] = self.class.class_name
        hash
      end
    end

    def self.from_hash(runtime, hash)
      hash.delete '__class'
      obj = self.new
      hash.each do |k, val|
        if val.is_a? Hash
          val = runtime.fetch(val['__class']).from_hash(runtime, val)
        end
        obj.send "#{k}=", val
      end
      obj
    end
    def self.unique_parent_accessors
      plain = Set.new(plain_accessors.map {|accessor| accessor.to_s.gsub(VAR_SUFIX, '').to_sym})
      parent_accessors = Set.new(roxml_attrs.map { |attr| attr.accessor })
      parent_accessors - plain
    end
    class_eval &block if block_given?
  end

end