refactoring register methods and API

This commit is contained in:
Gwenhael Le Moine 2014-07-27 22:04:00 +02:00
parent 90d343636e
commit 12a482b16e
2 changed files with 14 additions and 5 deletions

5
app.rb
View file

@ -27,15 +27,16 @@ class LedgerRbApp < Sinatra::Base
Ledger.accounts( params[ :depth ] ).to_json Ledger.accounts( params[ :depth ] ).to_json
end end
get '/api/ledger/monthly/?' do get '/api/ledger/register/:period/?' do
content_type :json content_type :json
param :period, String, required: true # TODO: restrict possible values to [ 'yearly', 'monthly' ]
param :categories, Array, default: Ledger.accounts( 1 ) param :categories, Array, default: Ledger.accounts( 1 )
params[ :categories ].map do params[ :categories ].map do
|category| |category|
cat = category.first cat = category.first
{ category: cat, { category: cat,
data: Ledger.monthly_register( cat ) } data: Ledger.register( cat, "--#{params[ :period ]}" ) }
end.to_json end.to_json
end end

View file

@ -29,15 +29,23 @@ module Ledger
run '', 'cleared' run '', 'cleared'
end end
def monthly_register( category ) def register( category, options='' )
run( "--monthly --collapse --amount-data --exchange '€'", 'register', "#{category}" ) run( "#{options} --collapse --amount-data --exchange '€'", 'register', "#{category}" )
.split( "\n" ) .split( "\n" )
.map do |line| .map do |line|
line_array = line.split line_array = line.split
{ date: line_array[ 0 ], { date: line_array[ 0 ],
amount: line_array[ 1 ].to_f } amount: line_array[ 1 ].to_f }
end end
end
def monthly_register( category )
register category, "--monthly"
end
def yearly_register( category )
register category, "--yearly"
end end
def balance( period = nil ) def balance( period = nil )