Class: ActiveRecord::Coders::YAMLColumn

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/coders/yaml_column.rb

Constant Summary collapse

RESCUE_ERRORS =
[ ArgumentError ]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object_class = Object) ⇒ YAMLColumn

Returns a new instance of YAMLColumn.



13
14
15
# File 'lib/active_record/coders/yaml_column.rb', line 13

def initialize(object_class = Object)
  @object_class = object_class
end

Instance Attribute Details

#object_classObject

Returns the value of attribute object_class.



11
12
13
# File 'lib/active_record/coders/yaml_column.rb', line 11

def object_class
  @object_class
end

Instance Method Details

#dump(obj) ⇒ Object



17
18
19
# File 'lib/active_record/coders/yaml_column.rb', line 17

def dump(obj)
  YAML.dump obj
end

#load(yaml) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/active_record/coders/yaml_column.rb', line 21

def load(yaml)
  return object_class.new if object_class != Object && yaml.nil?
  return yaml unless yaml.is_a?(String) && yaml =~ /^---/
  begin
    obj = YAML.load(yaml)

    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
    yaml
  end
end