Class: Kscript::KkUsdRateUtils

Inherits:
Base
  • Object
show all
Defined in:
lib/kscript/plugins/kk_usd_rate_utils.rb

Constant Summary collapse

API_URL =
'https://api.exchangerate-api.com/v4/latest/USD'

Instance Attribute Summary

Attributes inherited from Base

#logger

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#human_output?, inherited, #with_error_handling

Constructor Details

#initialize(currency_code = 'CNY', *args, **opts) ⇒ KkUsdRateUtils

Returns a new instance of KkUsdRateUtils.



15
16
17
18
# File 'lib/kscript/plugins/kk_usd_rate_utils.rb', line 15

def initialize(currency_code = 'CNY', *args, **opts)
  super(*args, **opts)
  @currency_code = currency_code
end

Class Method Details

.argumentsObject



41
42
43
# File 'lib/kscript/plugins/kk_usd_rate_utils.rb', line 41

def self.arguments
  '[currency_code]'
end

.authorObject



53
54
55
# File 'lib/kscript/plugins/kk_usd_rate_utils.rb', line 53

def self.author
  'kk'
end

.descriptionObject



57
58
59
# File 'lib/kscript/plugins/kk_usd_rate_utils.rb', line 57

def self.description
  'Get latest USD exchange rates.'
end

.groupObject



49
50
51
# File 'lib/kscript/plugins/kk_usd_rate_utils.rb', line 49

def self.group
  'finance'
end

.usageObject



45
46
47
# File 'lib/kscript/plugins/kk_usd_rate_utils.rb', line 45

def self.usage
  "kscript usd_rate CNY\nkscript usd_rate EUR"
end

Instance Method Details

#fetch_ratesObject



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/kscript/plugins/kk_usd_rate_utils.rb', line 27

def fetch_rates
  response = HTTPX.get(API_URL)
  response = response.first if response.is_a?(Array)
  data = JSON.parse(response.body.to_s)
  if @currency_code && data['rates'][@currency_code.upcase]
    rate = data['rates'][@currency_code.upcase]
    logger.kinfo("1 USD = #{rate} #{@currency_code.upcase}")
  elsif @currency_code
    logger.kerror("Currency code not found: #{@currency_code}")
  else
    logger.kinfo('USD rates', rates: data['rates'])
  end
end

#run(*args, **_opts) ⇒ Object



20
21
22
23
24
25
# File 'lib/kscript/plugins/kk_usd_rate_utils.rb', line 20

def run(*args, **_opts)
  with_error_handling do
    @currency_code = args[0] if args[0]
    fetch_rates
  end
end