Sha256: 5e0c5a5b3ea9780d7035b74879acd8b7761ace43e17a90c38151313d3add734e

Contents?: true

Size: 1.3 KB

Versions: 50

Compression:

Stored size: 1.3 KB

Contents

# 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) && /^---/.match?(yaml)
        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
    end
  end
end

Version data entries

50 entries across 50 versions & 7 rubygems

Version Path
activerecord-5.2.8 lib/active_record/coders/yaml_column.rb
activerecord-5.2.7.1 lib/active_record/coders/yaml_column.rb
activerecord-5.2.7 lib/active_record/coders/yaml_column.rb
activerecord-5.2.6.3 lib/active_record/coders/yaml_column.rb
activerecord-5.2.6.2 lib/active_record/coders/yaml_column.rb
activerecord-5.2.6.1 lib/active_record/coders/yaml_column.rb
activerecord-5.2.6 lib/active_record/coders/yaml_column.rb
activerecord-5.2.4.6 lib/active_record/coders/yaml_column.rb
activerecord-5.2.5 lib/active_record/coders/yaml_column.rb
activerecord-5.2.4.5 lib/active_record/coders/yaml_column.rb
activerecord-5.2.4.4 lib/active_record/coders/yaml_column.rb
activerecord-5.2.4.3 lib/active_record/coders/yaml_column.rb
activerecord-6.0.2.2 lib/active_record/coders/yaml_column.rb
activerecord-5.2.4.2 lib/active_record/coders/yaml_column.rb
argon-1.3.1 vendor/bundle/ruby/2.7.0/gems/activerecord-6.0.2.1/lib/active_record/coders/yaml_column.rb
symbolic_enum-1.1.5 vendor/bundle/ruby/2.7.0/gems/activerecord-6.0.2.1/lib/active_record/coders/yaml_column.rb
activerecord-6.0.2.1 lib/active_record/coders/yaml_column.rb
activerecord-5.2.4.1 lib/active_record/coders/yaml_column.rb
activerecord-6.0.2 lib/active_record/coders/yaml_column.rb
activerecord-6.0.2.rc2 lib/active_record/coders/yaml_column.rb