Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion lib/mongoid/attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def write_attribute(name, value)
localized = fields[field_name].try(:localized?)
attributes_before_type_cast[name.to_s] = value
typed_value = typed_value_for(field_name, value)
unless attributes[field_name] == typed_value || attribute_changed?(field_name)
unless attribute_will_not_change?(field_name, typed_value) || attribute_changed?(field_name)
attribute_will_change!(field_name)
end
if localized
Expand Down Expand Up @@ -366,5 +366,23 @@ def lookup_attribute_presence(name, value)
end
value.present?
end

# If `value` is a `BSON::Decimal128`, convert it to a `BigDecimal` for
# comparison purposes. This is necessary because `BSON::Decimal128` does
# not implement `#==` in a way that is compatible with `BigDecimal`.
def normalize_value(value)
value.is_a?(BSON::Decimal128) ? BigDecimal(value.to_s) : value
end

# Determine if the attribute will not change, by comparing the current
# value with the new value. The values are normalized to account for
# types that do not implement `#==` in a way that is compatible with
# each other, such as `BSON::Decimal128` and `BigDecimal`.
def attribute_will_not_change?(field_name, typed_value)
normalized_attribute = normalize_value(attributes[field_name])
normalized_typed_value = normalize_value(typed_value)

normalized_attribute == normalized_typed_value
end
end
end
13 changes: 13 additions & 0 deletions spec/mongoid/attributes_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1729,6 +1729,19 @@
end
end
end

context 'when map_big_decimal_to_decimal128 is enabled' do
config_override :map_big_decimal_to_decimal128, true

context 'when writing an identical number' do
let(:band) { Band.create!(name: 'Nirvana', sales: 123456.78).reload }

it 'does not mark the document as changed' do
band.sales = 123456.78
expect(band.changed?).to be false
end
end
end
end

describe "#typed_value_for" do
Expand Down