Skip to content

Instantly share code, notes, and snippets.

@spif
Created December 8, 2010 16:46
Show Gist options
  • Save spif/733534 to your computer and use it in GitHub Desktop.
Save spif/733534 to your computer and use it in GitHub Desktop.
class Voucher < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => :voucher_users
belongs_to :plan
def self.create_for_beta_user(user)
voucher = new
voucher.code = [4,4,4,4].map {|x| random_string(x) }.join("-")
voucher.expires_on = 2.months.from_now
voucher.price = 19
voucher.plan = Plan.premium
voucher.referrer = user.username
voucher.times_usable = 5
voucher.save!
voucher
end
def self.random_string(len = 4)
# The argument n specifies the length of the random length. The length of the result string is twice of n.
ActiveSupport::SecureRandom.hex(len/2)
end
def usable_by?(user)
usable? && !used_by?(user)
end
def used_by?(user)
!!users.find_by_id(user.id)
end
def usable?
(not expired?) and times_usable > 0
end
def expired?
expires_on.present? && expires_on < Time.now
end
def merchant_reference(user_id = self.user_id)
now = Time.now
[user_id, now.month, now.year, plan_length_type].join("-")
end
# use the voucher.
def use!(user)
users << user
self.decrement!(:times_usable)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment