Sha256: d089a82e9526dff28f6896dc45371917b5f046d65138fe62a1b03aa23295f6b9

Contents?: true

Size: 1006 Bytes

Versions: 1

Compression:

Stored size: 1006 Bytes

Contents

module ShallowAttributes
  module Type
    # This class cange object to Integer.
    #
    # @abstract
    #
    # @since 0.1.0
    class Integer
      # Convert value to Integer type
      #
      # @private
      #
      # @param [Object] value
      # @param [Hash] option
      # @option options [boolean] :allow_nil cast `nil` to integer or float
      #
      # @example Convert sting to integer value
      #   ShallowAttributes::Type::Integer.new.coerce('2001')
      #     # => 2001
      #
      # @raise [InvalidValueError] if values is invalid
      #
      # @return [Integer]
      #
      # @since 0.1.0
      def coerce(value, options = {})
        case value
        when nil then options[:allow_nil] ? 0 : nil
        when ::TrueClass then 1
        when ::FalseClass then 0
        else
          value.respond_to?(:to_i) ? value.to_i
            : raise(ShallowAttributes::Type::InvalidValueError, %(Invalid value "#{value}" for type "Integer"))
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
shallow_attributes-0.9.2 lib/shallow_attributes/type/integer.rb