Sha256: 98120d0bcd4e3c8e0383db009b18655660f88bb64747d6fee70c67b3e37cb7cc

Contents?: true

Size: 1.05 KB

Versions: 4

Compression:

Stored size: 1.05 KB

Contents

# frozen_string_literal: true

require "active_model"

module StoreModel
  module Types
    class EnumType < ActiveModel::Type::Value
      def initialize(mapping)
        @mapping = mapping
      end

      def type
        :integer
      end

      def cast_value(value)
        return if value.blank?

        case value
        when String, Symbol then cast_symbol_value(value.to_sym)
        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) unless @mapping.key?(value.to_sym)
        @mapping[value.to_sym]
      end

      def cast_integer_value(value)
        raise_invalid_value!(value) unless @mapping.value?(value)
        value
      end

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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
store_model-0.5.1 lib/store_model/types/enum_type.rb
store_model-0.5.0 lib/store_model/types/enum_type.rb
store_model-0.4.1 lib/store_model/types/enum_type.rb
store_model-0.4.0 lib/store_model/types/enum_type.rb