diff options
-rwxr-xr-x | blaunits.rb | 62 |
1 files changed, 57 insertions, 5 deletions
diff --git a/blaunits.rb b/blaunits.rb index 8c08e0f..39557a3 100755 --- a/blaunits.rb +++ b/blaunits.rb @@ -1,9 +1,41 @@ #!/usr/bin/ruby +require 'net/http' +require 'json' + VERSION = "2.1.0" BINARY_NAME = "units" begin + def get_crypto_id(currency_name) + url = 'https://api.coinmarketcap.com/v1/ticker/' + uri = URI(url) + response = Net::HTTP.get(uri) + currencies = JSON.parse(response) + currencies.each do |currency| + if currency["id"] == currency_name || currency["name"] == currency_name || currency["symbol"] == currency_name + return currency["id"] + end + end + return "" + end + + def get_crypto_price(currency_name, convert_name) + from_name = get_crypto_id(currency_name) + if from_name == "" + return "Error: Unknown unit '" + currency_name + "'" + end + url = 'https://api.coinmarketcap.com/v1/ticker/' + from_name + '/?convert=' + convert_name + uri = URI(url) + response = Net::HTTP.get(uri) + currencies = JSON.parse(response) + price = currencies[0]["price_" + convert_name.downcase] + if !price + return "Error: Incompatible units. Can't convert " + currency_name + " to " + convert_name + end + return price + end + args = ARGV.dup if args.empty? input = STDIN.gets @@ -70,14 +102,34 @@ begin out = %x(#{BINARY_NAME} -t1 #{from} #{to}) outs = out.split(" ") if outs[0] == "Unknown" - puts out - exit + out = "Error: " + out + units_failed = true + elsif outs[0] == "conformability" + out = "Error: Incompatible units. Can't convert from #{from} to #{to}" + units_failed = true end + elsif outs[0] == "conformability" + out = "Error: Incompatible units. Can't convert from #{from} to #{to}" + units_failed = true end elsif outs[0] == "conformability" - puts "Incompatible units. Can't convert from #{from} to #{to}" - exit + out = "Error: Incompatible units. Can't convert from #{from} to #{to}" + units_failed = true end + + if units_failed + units_error = out + out = get_crypto_price(from, to) + if out.split(" ")[0] == "Error:" + if units_error.split(" ")[1] == "Incompatible" + puts units_error + else + puts out + end + exit + end + end + puts "#{num} #{from} = #{num * Float(out)} #{to}" - end + end end |