Create a gist now

Instantly share code, notes, and snippets.

Happy Path for Splits
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment