File: yaml_column.rb

package info (click to toggle)
rails 2%3A4.2.7.1-1%2Bdeb9u2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 23,416 kB
  • sloc: ruby: 186,673; yacc: 45; sql: 43; sh: 14; makefile: 12
file content (38 lines) | stat: -rw-r--r-- 978 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
require 'yaml'

module ActiveRecord
  module Coders # :nodoc:
    class YAMLColumn # :nodoc:

      attr_accessor :object_class

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

      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
        YAML.dump obj
      end

      def load(yaml)
        return object_class.new if object_class != Object && yaml.nil?
        return yaml unless yaml.is_a?(String) && yaml =~ /^---/
        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
      end
    end
  end
end