Created
February 27, 2015 20:23
-
-
Save odigity/af0a954efe6e8cb561e0 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
class MembershipLevel | |
include Comparable | |
include ActiveModel::Validations | |
## Constants | |
MONTHLY = 10 | |
ANNUAL = 20 | |
LIFETIME = 30 | |
TO_S = { | |
MONTHLY => 'Monthly', | |
ANNUAL => 'Annual', | |
LIFETIME => 'Lifetime', | |
} | |
PRICE = { | |
MONTHLY => BigDecimal.new('50.00'), | |
ANNUAL => BigDecimal.new('500.00'), | |
LIFETIME => BigDecimal.new('2000.00'), | |
} | |
ALL = [MONTHLY, ANNUAL, LIFETIME] | |
## Fields | |
attr_accessor :value | |
## Validations | |
validates :value, inclusion: { in: ALL, message: "%{value} is not a valid membership level" } | |
## Constructor | |
def initialize(value) | |
unless value.nil? | |
@value = value.to_i | |
valid? or raise 'invalid value' | |
end | |
end | |
## Instance Methods | |
def <=>(other) | |
value <=> other.value | |
end | |
def annual? | |
value == ANNUAL | |
end | |
def eql?(other) | |
value == other.value | |
end | |
def hash | |
value | |
end | |
def label | |
value.nil? ? nil : TO_S[value] | |
end | |
def label_full | |
value.nil? ? nil : TO_S[value] + " Membership" | |
end | |
def lifetime? | |
value == LIFETIME | |
end | |
def monthly? | |
value == MONTHLY | |
end | |
def price | |
value.nil? ? nil : PRICE[value] | |
end | |
def to_i | |
value | |
end | |
def to_s | |
label | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment