forked from chicago-tool-library/circulate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgift_membership.rb
46 lines (37 loc) · 1.17 KB
/
gift_membership.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class GiftMembership < ApplicationRecord
monetize :amount_cents, numericality: {
greater_than_or_equal_to: 0
}
composed_of :code, class_name: "GiftMembershipCode", mapping: %w[code value], allow_nil: true
belongs_to :membership, required: false
validates :purchaser_email, format: {with: URI::MailTo::EMAIL_REGEXP, message: "must be a valid email"}
validates :purchaser_name, presence: true
validates :code, uniqueness: true, presence: true
before_validation :set_code, if: ->(gm) { gm.code.blank? }
def self.unique_code?(code)
where(code: code.value).count == 0
end
def redeem(membership)
update_attribute(:membership_id, membership.id)
end
# This is to work around an incompatibility between using composed_of and the
# built-in uniqueness validation.
def read_attribute_for_validation(attr)
if attr.to_sym == :code
code.try(:value)
else
super
end
end
private
def set_code
self.code = find_random_unique_code
end
def find_random_unique_code
5.times do |n|
code = GiftMembershipCode.random
return code if self.class.unique_code?(code)
end
raise "could not find a unique code"
end
end