Class: ShallowAttributes::Type::Integer Abstract

Inherits:
Object
  • Object
show all
Defined in:
lib/shallow_attributes/type/integer.rb

Overview

This class is abstract.

This class cange object to Integer.

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

#coerce(value, options = {}) ⇒ Integer

Convert value to Integer type

Examples:

Convert sting to integer value

ShallowAttributes::Type::Integer.new.coerce('2001')
  # => 2001

Parameters:

  • value (Object)
  • option (Hash)
  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :allow_nil (boolean)

    cast `nil` to integer or float

Returns:

Raises:

Since:

  • 0.1.0


26
27
28
29
30
31
32
33
34
35
# File 'lib/shallow_attributes/type/integer.rb', line 26

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