Created
February 17, 2018 04:03
-
-
Save anonymous/dc7f532787705126fc4a19dd43017235 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'sequel' | |
require 'json' | |
require './lib/currency' | |
DB = Sequel.connect('sqlite://db/wallets.db') | |
class WalletCentral | |
def self.output(name=nil) | |
if name.nil? | |
DB[:wallets].select_hash_groups(:name, [:currency, :amount]).to_json | |
else | |
DB[:wallets].where(name: name).select_hash_groups(:name, [:currency, :amount]).to_json | |
end | |
end | |
def self.transfer(from, to, currency, target_currency=nil, amount) | |
sender_currency = DB[:wallets].where(name: from, currency: currency).get(:currency) | |
recipient_currencies = DB[:wallets].where(name: to).select_map(:currency) | |
raise 'No such currency for sender' if sender_currency.nil? | |
if recipient_currencies.include?(sender_currency) && target_currency.nil? | |
DB.transaction do | |
DB[:wallets].where(name: from, currency: currency).update(amount: Sequel[:amount]-amount) | |
DB[:wallets].where(name: to, currency: currency).update(amount: Sequel[:amount]+amount) | |
end | |
else | |
price = Currency.new.convert(amount, target_currency) | |
DB.transaction do | |
DB[:wallets].where(name: from, currency: currency).update(amount: Sequel[:amount]-amount) | |
DB[:wallets].where(name: to, currency: target_currency).update(amount: Sequel[:amount]+price) | |
end | |
end | |
end | |
end | |
WalletCentral.transfer('jon', 'sansa', 'USD', 'BRL', 1) | |
puts WalletCentral.output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment