Sha256: 2f3aa7637c839c12fb1ebed0fd6f0f44cf6649eee58fe31ba42409e0089a4008

Contents?: true

Size: 1008 Bytes

Versions: 1

Compression:

Stored size: 1008 Bytes

Contents

module ShallowAttributes
  module Type
    # This class changes object to Integer.
    #
    # @abstract
    #
    # @since 0.1.0
    class Integer
      # Convert value to Integer type
      #
      # @private
      #
      # @param [Object] value
      # @param [Hash] options
      # @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 value is invalid
      #
      # @return [Integer]
      #
      # @since 0.1.0
      def coerce(value, options = {})
        case value
        when nil then options[:allow_nil] ? nil : 0
        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.5 lib/shallow_attributes/type/integer.rb