Module: Recognition::ActiveRecord::Voucher

Defined in:
lib/recognition/activerecord/voucher.rb

Instance Method Summary collapse

Instance Method Details

#redeem(recognizable) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/recognition/activerecord/voucher.rb', line 17

def redeem recognizable
  # Make sure we have an amount beforehand
  if defined? self.amount
    if self.redeemable? recognizable
      Database.redeem_voucher recognizable.id, self.code, self.amount
    end
  end
end

#redeemable?(recognizable) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/recognition/activerecord/voucher.rb', line 26

def redeemable? recognizable
  # default: not redeemable
  pass = false
  # has the voucher ever been redeemed?
  if Database.get_voucher_transactions(self.code).any?
    # has the voucher ever been redeemed by this user?
    if Database.get_user_voucher(recognizable.id, code) != 0
      pass = false
      # is the voucher reusable?
    elsif defined?(self.reusable?) && self.reusable?
      pass = true
    end
  else
    pass = true
  end
  pass
end

#regenerate_codeObject



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/recognition/activerecord/voucher.rb', line 4

def regenerate_code
  l = self.class.recognitions[:code_length] || 10
  dict = [('a'..'z'),('A'..'Z'),(0..9)].map{|i| i.to_a}.flatten
  code = (1..l).map{ dict[rand(dict.length)] }.join
  # Prevent code collision at all costs
  if self.class.to_s.constantize.find_all_by_code(code).any?
    regenerate_code
  else
    self.code = code
    self
  end
end