File: yaml_column.rb

package info (click to toggle)
rails 2%3A6.1.7.10%2Bdfsg-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 39,756 kB
  • sloc: ruby: 290,662; javascript: 19,241; yacc: 46; sql: 43; makefile: 32; sh: 18
file content (71 lines) | stat: -rw-r--r-- 2,367 bytes parent folder | download
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# frozen_string_literal: true

require "yaml"

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

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

      def dump(obj)
        return if obj.nil?

        assert_valid_value(obj, action: "dump")
        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.start_with?("---")
        obj = yaml_load(yaml)

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

        obj
      end

      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

      private
        def check_arity_of_constructor
          load(nil)
        rescue ArgumentError
          raise ArgumentError, "Cannot serialize #{object_class}. Classes passed to `serialize` must have a 0 argument constructor."
        end

        if YAML.respond_to?(:unsafe_load)
          def yaml_load(payload)
            if ActiveRecord::Base.use_yaml_unsafe_load
              YAML.unsafe_load(payload)
            elsif YAML.method(:safe_load).parameters.include?([:key, :permitted_classes])
              YAML.safe_load(payload, permitted_classes: ActiveRecord::Base.yaml_column_permitted_classes, aliases: true)
            else
              YAML.safe_load(payload, ActiveRecord::Base.yaml_column_permitted_classes, [], true)
            end
          end
        else
          def yaml_load(payload)
            if ActiveRecord::Base.use_yaml_unsafe_load
              YAML.load(payload)
            elsif YAML.method(:safe_load).parameters.include?([:key, :permitted_classes])
              YAML.safe_load(payload, permitted_classes: ActiveRecord::Base.yaml_column_permitted_classes, aliases: true)
            else
              YAML.safe_load(payload, ActiveRecord::Base.yaml_column_permitted_classes, [], true)
            end
          end
        end
    end
  end
end