Class: ActiveRecord::Coders::XMLColumn

Inherits:
Object
  • Object
show all
Defined in:
lib/serialize-rails/coders/xml_column.rb

Overview

:nodoc:

Constant Summary collapse

RESCUE_ERRORS =
[ ArgumentError, SyntaxError ]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object_class = Object, options = nil) ⇒ XMLColumn

Returns a new instance of XMLColumn.



10
11
12
13
14
15
# File 'lib/serialize-rails/coders/xml_column.rb', line 10

def initialize(object_class = Object, options = nil)
  @object_class = object_class
  @options = options || Hash.new
  default_options = { :load => Hash.new, :dump => Hash.new }
  @options = default_options.merge(@options)
end

Instance Attribute Details

#object_classObject

Returns the value of attribute object_class.



8
9
10
# File 'lib/serialize-rails/coders/xml_column.rb', line 8

def object_class
  @object_class
end

#optionsObject

Returns the value of attribute options.



8
9
10
# File 'lib/serialize-rails/coders/xml_column.rb', line 8

def options
  @options
end

Instance Method Details

#dump(obj) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/serialize-rails/coders/xml_column.rb', line 17

def dump(obj)
  return if obj.nil?

  unless obj.is_a?(object_class)
    raise SerializationTypeMismatch,
      "Attribute was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}"
  end
  Ox.dump(obj, options[:dump])
end

#load(xml) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/serialize-rails/coders/xml_column.rb', line 27

def load(xml)
  return object_class.new if object_class != Object && xml.nil?
  return xml unless xml.is_a?(String)
  begin
    default_load_opts = { :mode => :object }
    obj = Ox.load(xml, default_load_opts.merge(options[:load]))

    unless obj.is_a?(object_class) || obj.nil?
      raise SerializationTypeMismatch,
        "Attribute was supposed to be a #{object_class}, but was a #{obj.class}"
    end
    obj ||= object_class.new if object_class != Object

    obj
  rescue *RESCUE_ERRORS
    xml
  end
end