module Mongoid::Extensions::BigDecimal::ClassMethods

Public Instance Methods

demongoize(object) click to toggle source

Convert the object from its mongo friendly ruby type to this type.

@param [ Object ] object The object to demongoize.

@return [ BigDecimal | nil ] A BigDecimal derived from the object or nil.

# File lib/mongoid/extensions/big_decimal.rb, line 56
def demongoize(object)
  return if object.blank?
  if object.is_a?(BSON::Decimal128)
    object.to_big_decimal
  elsif object.numeric?
    object.to_d
  end
end
mongoize(object) click to toggle source

Mongoize an object of any type to how it’s stored in the db.

@example Mongoize the object.

BigDecimal.mongoize(123)

@param [ Object ] object The object to Mongoize

@return [ String | BSON::Decimal128 | nil ] A String or Decimal128

representing the object or nil. String if Mongoid.map_big_decimal_to_decimal128
is false, BSON::Decimal128 otherwise.
# File lib/mongoid/extensions/big_decimal.rb, line 75
def mongoize(object)
  return if object.blank?
  if Mongoid.map_big_decimal_to_decimal128
    if object.is_a?(BSON::Decimal128)
      object
    elsif object.is_a?(BigDecimal)
      BSON::Decimal128.new(object)
    elsif object.numeric?
      BSON::Decimal128.new(object.to_s)
    elsif !object.is_a?(String)
      object.try(:to_d)
    end
  else
    if object.is_a?(BSON::Decimal128) || object.numeric?
      object.to_s
    elsif !object.is_a?(String)
      object.try(:to_d)&.to_s
    end
  end
end