Class: ActiveAttr::Typecasting::BigDecimalTypecaster

Inherits:
Object
  • Object
show all
Defined in:
lib/active_attr/typecasting/big_decimal_typecaster.rb

Overview

Typecasts an Object to a BigDecimal

Examples:

Usage

BigDecimalTypecaster.new.call(1).to_s #=> "0.1E1"

Since:

  • 0.5.0

Instance Method Summary collapse

Instance Method Details

#call(value) ⇒ BigDecimal?

Typecasts an object to a BigDecimal

Attempt to convert using #to_d, else it creates a BigDecimal using the String representation of the value.

Examples:

Typecast an Integer

typecaster.call(1).to_s #=> "0.1E1"

Parameters:

  • value (Object, #to_d, #to_s)

    The object to typecast

Returns:

  • (BigDecimal, nil)

    The result of typecasting

Since:

  • 0.5.0



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/active_attr/typecasting/big_decimal_typecaster.rb', line 28

def call(value)
  if value.is_a? BigDecimal
    value
  elsif value.is_a? Rational
    value.to_f.to_d
  elsif value.blank?
    nil
  elsif value.respond_to? :to_d
    value.to_d
  else
    BigDecimal(value.to_s)
  end
rescue ArgumentError
  BigDecimal("0")
end