Sha256: 289c7311c1319ccca008f529c64ec07d81821524fd82d2caf4b3e0f39522ac0c

Contents?: true

Size: 1.9 KB

Versions: 1

Compression:

Stored size: 1.9 KB

Contents

module Coercible
  class Coercer

    # Coerce Fixnum values
    class Integer < Numeric
      extend Configurable

      primitive ::Integer

      config_keys [ :boolean_map ]

      # Return default config for Integer coercer type
      #
      # @return [Configuration]
      #
      # @see Configurable#config
      #
      # @api private
      def self.config
        super do |config|
          config.boolean_map = { 0 => false, 1 => true }
        end
      end

      # Return boolean map from config
      #
      # @return [::Hash]
      #
      # @api private
      attr_reader :boolean_map

      # Initialize a new Integer coercer instance and set its configuration
      #
      # @return [undefined]
      #
      # @api private
      def initialize(coercer = Coercer.new, config = self.class.config)
        super(coercer)
        @boolean_map     = config.boolean_map
      end

      # Coerce given value to String
      #
      # @example
      #   coercer[Integer].to_string(1)  # => "1"
      #
      # @param [Fixnum] value
      #
      # @return [String]
      #
      # @api public
      def to_string(value)
        value.to_s
      end

      # Passthrough the value
      #
      # @example
      #   coercer[Integer].to_integer(1)  # => 1
      #
      # @param [Fixnum] value
      #
      # @return [Float]
      #
      # @api public
      def to_integer(value)
        value
      end

      # Coerce given value to a Boolean
      #
      # @example with a 1
      #   coercer[Integer].to_boolean(1)  # => true
      #
      # @example with a 0
      #   coercer[Integer].to_boolean(0)  # => false
      #
      # @param [Fixnum] value
      #
      # @return [BigDecimal]
      #
      # @api public
      def to_boolean(value)
        boolean_map.fetch(value) {
          raise_unsupported_coercion(value, __method__)
        }
      end

    end # class Fixnum

  end # class Coercer
end # module Coercible

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
motion_coercible-0.2.0 lib/project/coercer/integer.rb