Skip to content

Commit

Permalink
Introduce from_json as the inverse of to_json
Browse files Browse the repository at this point in the history
  • Loading branch information
pedropb committed Aug 13, 2024
1 parent 1049cf3 commit ddc3195
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/money/money.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# frozen_string_literal: true
require 'forwardable'
require 'json'

class Money
include Comparable
Expand Down Expand Up @@ -74,6 +75,16 @@ def from_subunits(subunits, currency_iso, format: :iso4217)
new(value, currency)
end

def from_json(hash_or_string)
hash = if hash_or_string.is_a?(Hash)
hash_or_string.transform_keys(&:to_sym)
else
JSON.parse(hash_or_string, symbolize_names: true)
end

Money.new(hash.fetch(:value), hash.fetch(:currency))
end

def rational(money1, money2)
money1.send(:arithmetic, money2) do
factor = money1.currency.subunit_to_unit * money2.currency.subunit_to_unit
Expand Down
22 changes: 22 additions & 0 deletions spec/money_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,28 @@
expect(JSON.dump(Money.new(1.00, "CAD"))).to eq('{"value":"1.00","currency":"CAD"}')
end

it "creates Money object from #as_json output" do
one_cad = Money.new(1, "CAD")
expect(Money.from_json(one_cad.as_json)).to eq(one_cad)
end

it "creates Money object from #to_json output" do
one_cad = Money.new(1, "CAD")
expect(Money.from_json(one_cad.to_json)).to eq(one_cad)
end

it "creates Money object from JSON-encoded string" do
expect(Money.from_json('{ "value": 1.01, "currency": "CAD" }')).to eq(Money.new(1.01, "CAD"))
end

it "creates Money object from JSON-encoded hash" do
expect(Money.from_json({value: 1.01, currency: "CAD" })).to eq(Money.new(1.01, "CAD"))
end

it "raises if JSON Hash is malformed in from_json" do
expect { Money.from_json({ "val": 1.0 }) }.to raise_error(KeyError)
end

it "supports absolute value" do
expect(Money.new(-1.00).abs).to eq(Money.new(1.00))
end
Expand Down

0 comments on commit ddc3195

Please sign in to comment.