Sha256: 586fc6566ec9f1372c4ff7bbbeac865818c02e6dd9ac31b0fae2dfdb7c321bbb

Contents?: true

Size: 811 Bytes

Versions: 13

Compression:

Stored size: 811 Bytes

Contents

module ActiveRecord
  module Enum
    class EnumType < Type::Value # :nodoc:
      delegate :type, to: :subtype

      def initialize(name, mapping, subtype)
        @name = name
        @mapping = mapping
        @subtype = subtype
      end

      def cast(value)
        return if value.blank?

        if valid?(value)
          value.to_sym
        else
          assert_valid_value(value)
        end
      end

      def deserialize(value)
        value&.to_sym
      end

      def serialize(value)
        value ? value.to_s : nil
      end

      def valid?(value)
        mapping.include?(value.to_s)
      end

      def assert_valid_value(value)
        unless value.blank? || valid?(value)
          raise ArgumentError, "'#{value}' is not a valid #{name}"
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
sql_enum-0.2.2 lib/active_record/enum/enum_type.rb
sql_enum-0.2.1 lib/active_record/enum/enum_type.rb
sql_enum-0.1.18 lib/active_record/enum/enum_type.rb
sql_enum-0.1.17 lib/active_record/enum/enum_type.rb
sql_enum-0.1.16 lib/active_record/enum/enum_type.rb
sql_enum-0.1.15 lib/active_record/enum/enum_type.rb
sql_enum-0.1.14 lib/active_record/enum/enum_type.rb
sql_enum-0.1.13 lib/active_record/enum/enum_type.rb
sql_enum-0.1.12 lib/active_record/enum/enum_type.rb
sql_enum-0.1.11 lib/active_record/enum/enum_type.rb
sql_enum-0.1.10 lib/active_record/enum/enum_type.rb
sql_enum-0.1.9 lib/active_record/enum/enum_type.rb
sql_enum-0.1.8 lib/active_record/enum/enum_type.rb