Currency: Behavior change for to_json for demurrage currencies.

Currency#to_json should output a format that can be successfully converted back
to a Currency object via from_json. So for demurrage currencies it should output
the full hex currency code.

Currency#to_human on the other hand should always print something a human will
understand. For demurrage currencies we'll print the three-letter code for now.
This commit is contained in:
Stefan Thomas
2014-02-09 23:05:30 -08:00
parent 37e6d95cbc
commit 0772ffb6ed
2 changed files with 24 additions and 4 deletions

View File

@@ -193,11 +193,13 @@ Currency.prototype.get_interest_at = function (referenceDate) {
Currency.prototype.to_json = function () {
if (!this.is_valid()) {
// XXX This backwards compatible behavior, but probably not very good.
// XXX This is backwards compatible behavior, but probably not very good.
return "XRP";
}
if (/^[A-Z0-9]{3}$/.test(this._iso_code)) {
// Any currency with standard properties and a valid code can be abbreviated
// in the JSON wire format as the three character code.
if (/^[A-Z0-9]{3}$/.test(this._iso_code) && !this.has_interest()) {
return this._iso_code;
}
@@ -215,6 +217,11 @@ Currency.prototype.to_json = function () {
};
Currency.prototype.to_human = function () {
// to_human() will always print the human-readable currency code if available.
if (/^[A-Z0-9]{3}$/.test(this._iso_code)) {
return this._iso_code;
}
return this.to_json();
};

View File

@@ -10,8 +10,9 @@ describe('Currency', function() {
it('json_rewrite("NaN") == "XRP"', function() {
assert.strictEqual('XRP', currency.json_rewrite(NaN));
});
it('json_rewrite("015841551A748AD2C1F76FF6ECB0CCCD00000000") == "XAU"', function() {
assert.strictEqual('XAU', currency.json_rewrite("015841551A748AD2C1F76FF6ECB0CCCD00000000"));
it('json_rewrite("015841551A748AD2C1F76FF6ECB0CCCD00000000") == "015841551A748AD2C1F76FF6ECB0CCCD00000000"', function() {
assert.strictEqual(currency.json_rewrite("015841551A748AD2C1F76FF6ECB0CCCD00000000"),
'015841551A748AD2C1F76FF6ECB0CCCD00000000');
});
});
describe('from_json', function() {
@@ -27,6 +28,18 @@ describe('Currency', function() {
assert.strictEqual('XRP', r.to_json());
});
});
describe('to_human', function() {
it('"USD".to_human() == "USD"', function() {
assert.strictEqual('USD', currency.from_json('USD').to_human());
});
it('"NaN".to_human() == "XRP"', function() {
assert.strictEqual('XRP', currency.from_json(NaN).to_human());
});
it('"015841551A748AD2C1F76FF6ECB0CCCD00000000") == "015841551A748AD2C1F76FF6ECB0CCCD00000000"', function() {
assert.strictEqual(currency.from_json("015841551A748AD2C1F76FF6ECB0CCCD00000000").to_human(),
'XAU');
});
});
describe('parse_json(currency obj)', function() {
assert.strictEqual('USD', new currency().parse_json(currency.from_json('USD')).to_json());
});