Class: ShallowAttributes::Type::Float Abstract

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

Overview

This class is abstract.

This class needs for cange object type to Float.

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

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

Convert value to Float type

Examples:

Convert string to float value

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

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/float.rb', line 26

def coerce(value, options = {})
  case value
  when nil then options[:allow_nil] ? 0.0 : nil
  when ::TrueClass then 1.0
  when ::FalseClass then 0.0
  else
    value.respond_to?(:to_f) ? value.to_f
      : raise(ShallowAttributes::Type::InvalidValueError, %(Invalid value "#{value}" for type "Float"))
  end
end