Skip to content

Instantly share code, notes, and snippets.

@sterrym
Created October 6, 2009 16:33
Show Gist options
  • Save sterrym/203177 to your computer and use it in GitHub Desktop.
Save sterrym/203177 to your computer and use it in GitHub Desktop.
class Charge < ActiveRecord::Base
CHARGE_TYPES = ["upload", "storage", "deposit"]
belongs_to :member
default_scope :order => "charges.updated_at DESC"
validates_presence_of :name, :unit_price, :quantity
validates_inclusion_of :charge_type, :in => CHARGE_TYPES
validates_inclusion_of :chargeable_type, :in => %w(Payment VideoUpload)
before_save :adjust_unit_price
after_create :adjust_member_balance!
def total
self.unit_price * self.quantity
end
private
def adjust_unit_price
return if unit_price.nil?
val = BigDecimal.new(unit_price.to_s)
val = self.charge_type == "deposit" ? val.abs : val.abs * -1
self.unit_price = val
end
def adjust_member_balance!
self.member.balance = member.balance + total
self.member.save!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment