Sha256: ebe6d3486d88ec231d591bc7a6b68625845b5c1e933d25f8469dac9e27b63231

Contents?: true

Size: 1.99 KB

Versions: 10

Compression:

Stored size: 1.99 KB

Contents

# frozen_string_literal: true

require "active_model"

module StoreModel
  module Types
    # Implements ActiveModel::Type::Value type for handling an array of
    # StoreModel::Model
    class ManyBase < ActiveModel::Type::Value
      # Returns type
      #
      # @return [Symbol]
      def type
        raise NotImplementedError
      end

      # Casts +value+ from DB or user to StoreModel::Model instance
      #
      # @param value [Object] a value to cast
      #
      # @return StoreModel::Model
      def cast_value(value)
        case value
        when String then decode_and_initialize(value)
        when Array then ensure_model_class(value)
        when nil then value
        else
          raise_cast_error(value)
        end
      end

      # Casts a value from the ruby type to a type that the database knows how
      # to understand.
      #
      # @param value [Object] value to serialize
      #
      # @return [String] serialized value
      def serialize(value)
        case value
        when Array
          ActiveSupport::JSON.encode(value)
        else
          super
        end
      end

      # Determines whether the mutable value has been modified since it was read
      #
      # @param raw_old_value [Object] old value
      # @param new_value [Object] new value
      #
      # @return [Boolean]
      def changed_in_place?(raw_old_value, new_value)
        cast_value(raw_old_value) != new_value
      end

      protected

      def ensure_model_class(_array)
        raise NotImplementedError
      end

      def cast_model_type_value(_value)
        raise NotImplementedError
      end

      def raise_cast_error(_value)
        raise NotImplementedError
      end

      private

      # rubocop:disable Style/RescueModifier
      def decode_and_initialize(array_value)
        decoded = ActiveSupport::JSON.decode(array_value) rescue []
        decoded.map { |attributes| cast_model_type_value(attributes) }
      end
      # rubocop:enable Style/RescueModifier
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
store_model-1.0.0 lib/store_model/types/many_base.rb
store_model-0.13.0 lib/store_model/types/many_base.rb
store_model-0.12.0 lib/store_model/types/many_base.rb
store_model-0.11.1 lib/store_model/types/many_base.rb
store_model-0.11.0 lib/store_model/types/many_base.rb
store_model-0.10.0 lib/store_model/types/many_base.rb
store_model-0.9.0 lib/store_model/types/many_base.rb
store_model-0.8.2 lib/store_model/types/many_base.rb
store_model-0.8.1 lib/store_model/types/many_base.rb
store_model-0.8.0 lib/store_model/types/many_base.rb