Sha256: f82c83c330f1a63f83c917dc3378bcb3ba0209b745ca0eb95ca2d1d6c0c5f34c

Contents?: true

Size: 1.62 KB

Versions: 5

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

require "active_model"

module StoreModel
  module Types
    # Implements ActiveModel::Type::Value type for handling Rails-like enums
    class EnumType < ActiveModel::Type::Value
      # Initializes type for mapping
      #
      # @param mapping [Hash] mapping for enum values
      #
      # @return [StoreModel::Types::EnumType]
      def initialize(mapping, raise_on_invalid_values)
        @mapping = mapping
        @raise_on_invalid_values = raise_on_invalid_values
      end

      # Returns type
      #
      # @return [Symbol]
      def type
        :integer
      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)
        return if value.blank?

        case value
        when String, Symbol then cast_symbol_value(value)
        when Integer then cast_integer_value(value)
        else
          raise StoreModel::Types::CastError,
                "failed casting #{value.inspect}, only String, Symbol or " \
                "Integer instances are allowed"
        end
      end

      private

      def cast_symbol_value(value)
        raise_invalid_value!(value) if @raise_on_invalid_values && !@mapping.key?(value.to_sym)
        @mapping[value.to_sym] || value
      end

      def cast_integer_value(value)
        raise_invalid_value!(value) if @raise_on_invalid_values && !@mapping.value?(value)
        value
      end

      def raise_invalid_value!(value)
        raise ArgumentError, "invalid value '#{value}' is assigned"
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
store_model-3.0.2 lib/store_model/types/enum_type.rb
store_model-3.0.1 lib/store_model/types/enum_type.rb
store_model-3.0.0 lib/store_model/types/enum_type.rb
store_model-2.4.0 lib/store_model/types/enum_type.rb
store_model-2.3.0 lib/store_model/types/enum_type.rb