From 2085cf77bba5c9c72b2a855365a192aaa8ea1be6 Mon Sep 17 00:00:00 2001 From: Joe Robinson Date: Thu, 9 Nov 2017 16:25:04 +0000 Subject: Add ability to convert cryptocurrency using coinmarketcap.com --- blaunits.rb | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 59 insertions(+), 8 deletions(-) diff --git a/blaunits.rb b/blaunits.rb index 13dc2aa..ffa6578 100755 --- a/blaunits.rb +++ b/blaunits.rb @@ -1,9 +1,41 @@ #!/usr/bin/ruby -VERSION = "2.0.2" -BINARY_NAME = "gunits" +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 @@ -63,14 +95,33 @@ 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 \ No newline at end of file +end -- cgit v1.2.3