2014-09-09 19:06:38 -07:00
|
|
|
class Donation < ActiveRecord::Base
|
2014-09-09 21:16:02 -07:00
|
|
|
FEATURE_COST = 500 # in cents = $5.00
|
|
|
|
|
2014-09-09 20:04:17 -07:00
|
|
|
attr_accessible :donor_name
|
|
|
|
|
2014-09-09 19:06:38 -07:00
|
|
|
belongs_to :user
|
2014-09-09 21:16:02 -07:00
|
|
|
has_many :features, class_name: 'DonationFeature'
|
2014-09-09 19:06:38 -07:00
|
|
|
|
2014-09-09 20:04:17 -07:00
|
|
|
def to_param
|
|
|
|
"#{id}-#{secret}"
|
|
|
|
end
|
|
|
|
|
2014-09-09 19:06:38 -07:00
|
|
|
def self.create_from_charge(user, params)
|
|
|
|
amount = (BigDecimal.new(params[:amount]) * 100).floor
|
|
|
|
|
|
|
|
customer = Stripe::Customer.create(
|
|
|
|
card: params[:stripe_token]
|
|
|
|
)
|
|
|
|
|
|
|
|
charge = Stripe::Charge.create(
|
|
|
|
:customer => customer.id,
|
|
|
|
:amount => amount,
|
|
|
|
:description => 'Donation (thank you!)',
|
|
|
|
:currency => 'usd'
|
|
|
|
)
|
|
|
|
|
|
|
|
donation = Donation.new
|
|
|
|
donation.amount = amount
|
|
|
|
donation.charge_id = charge.id
|
|
|
|
donation.user_id = user.try(:id)
|
2014-09-09 20:04:17 -07:00
|
|
|
donation.donor_name = user.try(:name)
|
|
|
|
donation.secret = new_secret
|
2014-09-09 21:16:02 -07:00
|
|
|
|
|
|
|
num_features = amount / FEATURE_COST
|
|
|
|
features = []
|
|
|
|
num_features.times do
|
|
|
|
features << donation.features.new
|
|
|
|
end
|
|
|
|
|
|
|
|
Donation.transaction do
|
|
|
|
donation.save!
|
|
|
|
features.each(&:save!)
|
|
|
|
end
|
2014-09-09 19:06:38 -07:00
|
|
|
|
|
|
|
donation
|
|
|
|
end
|
2014-09-09 20:04:17 -07:00
|
|
|
|
|
|
|
def self.new_secret
|
|
|
|
SecureRandom.urlsafe_base64 8
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.from_param(param)
|
|
|
|
id, secret = param.split('-', 2)
|
|
|
|
self.where(secret: secret).find(id)
|
|
|
|
end
|
2014-09-09 19:06:38 -07:00
|
|
|
end
|