Class: ActiveRecord::Coders::YAMLColumn

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

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attr_name, object_class = Object) ⇒ YAMLColumn

Returns a new instance of YAMLColumn.



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

def initialize(attr_name, object_class = Object)
  @attr_name = attr_name
  @object_class = object_class
  check_arity_of_constructor
end

Instance Attribute Details

#object_classObject

Returns the value of attribute object_class



8
9
10
# File 'activerecord/lib/active_record/coders/yaml_column.rb', line 8

def object_class
  @object_class
end

Instance Method Details

#assert_valid_value(obj, action:) ⇒ Object



34
35
36
37
38
39
# File 'activerecord/lib/active_record/coders/yaml_column.rb', line 34

def assert_valid_value(obj, action:)
  unless obj.nil? || obj.is_a?(object_class)
    raise SerializationTypeMismatch,
      "can't #{action} `#{@attr_name}`: was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}"
  end
end

#dump(obj) ⇒ Object



16
17
18
19
20
21
# File 'activerecord/lib/active_record/coders/yaml_column.rb', line 16

def dump(obj)
  return if obj.nil?

  assert_valid_value(obj, action: "dump")
  YAML.dump obj
end

#load(yaml) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'activerecord/lib/active_record/coders/yaml_column.rb', line 23

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

  assert_valid_value(obj, action: "load")
  obj ||= object_class.new if object_class != Object

  obj
end