aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/types/serialize.rb
blob: 7b6af1981f9121ebf1f55744e404a7fc8f31af6d (plain) (blame)
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
module ActiveRecord
  module Type
    class Serialize < Object

      def cast(value)
        unserialize(value)
      end

      def appendable?
        true
      end

      protected

      def unserialize(value)
        unserialized_object = object_from_yaml(value)

        if unserialized_object.is_a?(@options[:serialize]) || unserialized_object.nil?
          unserialized_object
        else
          raise SerializationTypeMismatch,
            "#{name} was supposed to be a #{@options[:serialize]}, but was a #{unserialized_object.class.to_s}"
        end
      end

      def object_from_yaml(string)
        return string unless string.is_a?(String) && string =~ /^---/
        YAML::load(string) rescue string
      end

    end
  end
end