historical: Normalize class instantiation for formatters.
This will make them easier to extend with different price/cost rates, and to add a Beancount formatter.
This commit is contained in:
parent
80fd49a98a
commit
fb2114896d
1 changed files with 15 additions and 12 deletions
|
@ -12,15 +12,18 @@ except ImportError:
|
|||
import enum34 as enum
|
||||
|
||||
class Formatter:
|
||||
def __init__(self, rate, signed_currencies=(), base_fmt='#,##0.###'):
|
||||
def __init__(self, rate, signed_currencies=(), base_fmt='#,##0.###',
|
||||
rate_precision=5, denomination=None):
|
||||
self.rate = rate
|
||||
self.base_fmt = base_fmt
|
||||
self.base_fmt_noprec = base_fmt.rsplit('.', 1)[0]
|
||||
self.signed_currencies = set(code for code in signed_currencies
|
||||
if self.can_sign_currency(code))
|
||||
self.rate_prec = rate_precision
|
||||
self.denomination = denomination
|
||||
|
||||
def can_sign_currency(self, code):
|
||||
return len(babel.numbers.get_currency_symbol(code)) == 1
|
||||
return False
|
||||
|
||||
def format_currency(self, amount, code, currency_digits=True):
|
||||
if currency_digits:
|
||||
|
@ -37,6 +40,9 @@ class Formatter:
|
|||
amt_s = babel.numbers.format_currency(amount, currency, '###0.###')
|
||||
return decimal.Decimal(amt_s)
|
||||
|
||||
def normalize_rate(self, rate, prec=None):
|
||||
return rate
|
||||
|
||||
def format_rate(self, rate):
|
||||
return "{:g}".format(rate)
|
||||
|
||||
|
@ -64,11 +70,8 @@ class Formatter:
|
|||
|
||||
|
||||
class LedgerFormatter(Formatter):
|
||||
def __init__(self, rate, signed_currencies=(), base_fmt='#,##0.###',
|
||||
rate_precision=5, denomination=None):
|
||||
super().__init__(rate, signed_currencies, base_fmt)
|
||||
self.rate_prec = rate_precision
|
||||
self.denomination = denomination
|
||||
def can_sign_currency(self, code):
|
||||
return len(babel.numbers.get_currency_symbol(code)) == 1
|
||||
|
||||
def normalize_rate(self, rate, prec=None):
|
||||
if prec is None:
|
||||
|
@ -150,11 +153,11 @@ def run(config, stdout, stderr):
|
|||
rate = oxrrate.Rate.from_json_file(rate_json)
|
||||
if loaders.should_cache():
|
||||
config.cache.save_rate(rate)
|
||||
if config.args.output_format is Formats.LEDGER:
|
||||
formatter = LedgerFormatter(rate, config.args.signed_currencies,
|
||||
denomination=config.args.denomination)
|
||||
else:
|
||||
formatter = Formatter(rate)
|
||||
formatter = config.args.output_format.value(
|
||||
rate,
|
||||
config.args.signed_currencies,
|
||||
denomination=config.args.denomination,
|
||||
)
|
||||
if not config.args.from_currency:
|
||||
for from_curr in sorted(rate.rates):
|
||||
print(formatter.format_rate_pair_bidir(from_curr, config.args.to_currency),
|
||||
|
|
Loading…
Reference in a new issue