class SimpleTax::Client

Attributes

api_endpoint[R]
redirect_url[R]
token[R]

Public Class Methods

new(options={}) click to toggle source
# File lib/simpletax.rb, line 21
def initialize(options={})
  @api_endpoint = options[:site]          || BASE_API
  @redirect_url = options[:redirect_url]  || raise("Redirect URL needed")
  client_id     = options[:client_id]     || raise("client_id needed")
  client_secret = options[:client_secret] || raise("client_secret needed")
  @client = OAuth2::Client.new(
    client_id,
    client_secret,
    site: api_endpoint,
    authorize_url: OAUTH_AUTHZ_URL,
    token_url: OAUTH_TOKEN_URL
  )
end

Public Instance Methods

add_expense(amount, optionals={}) click to toggle source
# File lib/simpletax.rb, line 53
def add_expense(amount, optionals={})
  requires_token!
  description = optionals[:description] || ''
  date        = optionals[:date]        || today
  date        = format_date(date)

  data = json_body value: amount, date: date, reference: description
  parse_response token.post(url('/expenses'), body: data)
end
add_income(amount, optionals={}) click to toggle source
# File lib/simpletax.rb, line 43
def add_income(amount, optionals={})
  requires_token!
  description = optionals[:description] || ''
  date        = optionals[:date]        || today
  date        = format_date(date)

  data = json_body value: amount, date: date, reference: description
  parse_response token.post(url('/incomes'), body: data)
end
authorize_url() click to toggle source
# File lib/simpletax.rb, line 35
def authorize_url
  @client.auth_code.authorize_url(redirect_uri: redirect_url)
end
fetch_token(code) click to toggle source
# File lib/simpletax.rb, line 39
def fetch_token(code)
  @token = @client.auth_code.get_token(code, redirect_uri: redirect_url)
end

Private Instance Methods

format_date(date) click to toggle source
# File lib/simpletax.rb, line 77
def format_date(date)
  date.to_date.strftime('%d/%m/%Y')
end
json_body(params) click to toggle source
# File lib/simpletax.rb, line 65
def json_body params
  MultiJson.dump fields: params
end
parse_error(resp) click to toggle source
# File lib/simpletax.rb, line 93
def parse_error resp
  status = resp.status
  if status >= 500
    raise ServerError.new status
  else
    raise NoAccessError.new status
  end
end
parse_response(resp) click to toggle source
# File lib/simpletax.rb, line 85
def parse_response resp
  if resp.status >= 400
    parse_error resp
  else
    resp.parsed
  end
end
requires_token!() click to toggle source
# File lib/simpletax.rb, line 73
def requires_token!
  raise 'Token needed' unless @token
end
today() click to toggle source
# File lib/simpletax.rb, line 81
def today
  Date.today
end
url(path) click to toggle source
# File lib/simpletax.rb, line 69
def url(path)
  "#{api_endpoint}#{path}"
end