Created
March 2, 2014 19:07
-
-
Save dannymcc/9311865 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# == Schema Information | |
# | |
# Table name: vouchers | |
# | |
# id :integer not null, primary key | |
# client_id :integer | |
# code :string(255) | |
# claimed :boolean default(FALSE) | |
# claimed_at :datetime | |
# created_at :datetime not null | |
# updated_at :datetime not null | |
# animal_id :integer | |
# expires_at :datetime | |
# | |
class Voucher < ActiveRecord::Base | |
attr_accessible :client_id, :animal_id, :claimed, :claimed_at, :expires_at | |
belongs_to :client | |
belongs_to :animal | |
validates_presence_of :client_id, :code | |
before_validation(on: :create) { | |
generate_token(:code) | |
self.expires_at = DateTime.now + 3.months | |
} | |
# If the voucher hasn't been claimed and was created 3 months ago | |
# then it will be expired | |
def expired? | |
if claimed == true | |
true | |
elsif DateTime.now > expires_at | |
true | |
else | |
false | |
end | |
end | |
# Marks the voucher as claimed and sets the date & time it was | |
# but only if it isn't already claimed | |
def claim! | |
unless claimed == true | |
self.claimed = true | |
self.claimed_at = DateTime.now | |
self.save! | |
end | |
end | |
def self.search(search, page) | |
paginate per_page: 10, page: page, conditions: ["code like ?", "%#{search}%"], order: "code" | |
end | |
protected | |
def generate_token(column) | |
begin | |
self[column] = SecureRandom.hex(3).upcase | |
end while Voucher.exists?(column => self[column]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment