Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FIX+Spec] Fractional not being BigDecimal upon deserialization #232

Merged
merged 3 commits into from Dec 5, 2012
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/money/money.rb
Expand Up @@ -25,7 +25,8 @@ def fractional
if self.class.infinite_precision
@fractional
else
@fractional.round(0, self.class.rounding_mode).to_i
# If the Money object is created from a serialized YAML string, @fractional can end up being set to a Float. We need to ensure it is BigDecimal before calling #round with two paramers. Float class only provides #round with 0 or 1 parameter.
BigDecimal.new(@fractional, 0).round(0, self.class.rounding_mode).to_i
end
end

Expand Down
29 changes: 29 additions & 0 deletions spec/money_spec.rb
Expand Up @@ -146,6 +146,35 @@ def expectation.fractional
m.fractional.should be_a(Fixnum)
end
end

it "when loading a serialized Money object from YAML fractional rounding always works on bigdecimal" do
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

context "loading a serialized Money via YAML" do
  it "uses BigDecimal when rounding" do

# Loading a YAML serialized money object is a common use case when dealing with persisting the money object in a queue, for example delayed_job
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No real need for this comment, the context+spec should be enough. Also, always try to respect 80 character line widths.

serialized = <<YAML
!ruby/object:Money
fractional: 249.5
currency: !ruby/object:Money::Currency
id: :eur
priority: 2
iso_code: EUR
name: Euro
symbol: €
alternate_symbols: []
subunit: Cent
subunit_to_unit: 100
symbol_first: true
html_entity: ! '&#x20AC;'
decimal_mark: ! ','
thousands_separator: .
iso_numeric: '978'
mutex: !ruby/object:Mutex {}
last_updated: 2012-11-23 20:41:47.454438399 +02:00
YAML
m = YAML::load serialized
m.should be_a(Money)
m.class.infinite_precision.should == false
m.fractional.should == 250 # 249.5 rounded up
m.fractional.should be_a(Integer)
end

context "user changes rounding_mode" do
after do
Expand Down