public
Last active

Happy Path for Splits

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
# user.rb
 
class User < ActiveRecord::Base
# create a balanced account for each new user
before_create :create_balanced_account
# credit_card_uri and bank_account_uri are tokenized client side
# in webviews using balanced.js
attr_accessible :account_uri,
:credit_card_uri,
:bank_account_uri
# add the tokenized bank account uri to our user's balanced account
def bank_account_uri=(uri)
api_client.bank_account_uri = uri
api_client.save
end
# add the tokenized bank account uri to our user's balanced account
def credit_card_uri=(uri)
api_client.add_card(uri)
end
 
# calling credit on the users bank account will use their latest added bank account,
# if a user has multiple accounts, you can specify which uri to credit
def credit(*args)
api_client.credit(args)
end
# calling debit on the users bank account will charge their latest added bank account,
# if a user has multiple accounts, you can specify which uri to credit
def debit(*args)
api_client.debit(args)
end
private
# all you need to create an account is an email address and a name.
def create_balanced_account
Balanced::Marketplace.mine.create_account({
email_address: email,
name: name
})
end
# this returns an instance of Balanced::Account
def api_client
@api_client ||= Balanced::Account.find(account_uri)
end
end
 
# split.rb - represents a purchase to be split by a group of users
 
class Split < ActiveRecord::Base
belongs_to :creator, class_name: "User"
has_many :users, through: :commitments
attr_accessible :total,
:price_per_person,
:creator_id,
:locked,
:total_escrowed
# this credits the collector's bank account with the total amount
# that we have a record of escrowing from the members
def collect!
credit = user.credit({
amount: total_escrowed,
description: title
})
if credit
update_attribute(:credit_uri, credit.uri)
true
else
update_attribute(:locked, false)
false
end
end
end
 
# commitment.rb - this links a user chipping in to a split
 
class Commitment < ActiveRecord::Base
belongs_to :user
belongs_to :split
# this debits the price of the split per person from the user's credit card
def charge!
charge = user.debit({
amount: split.price_per_person_with_fees,
appears_on_statement_as: split.title,
})
if charge
split.total_escrowed += split.price_per_person
split.save
update_attribute :debit_uri, charge.uri
charge.uri
else
false
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.