Skip to content

Instantly share code, notes, and snippets.

@avit
Created May 31, 2010 22:21
Show Gist options
  • Save avit/420332 to your computer and use it in GitHub Desktop.
Save avit/420332 to your computer and use it in GitHub Desktop.
# an example of composition using value classes
class Person < ActiveRecord::Base
# "gender" (string) column will use Gender value class
# to represent it instead of string
composed_of :gender
end
class Gender
include Comparable
attr_reader :gender
VALID_ENUMS = [:male, :female]
class InequalityError < StandardError; end
def initialize(value)
value = value.to_s.downcase.to_sym
@gender = value if VALID_ENUMS.include?(value)
end
def ==(other)
gender == other.gender
end
def <=>(other)
#VALID_ENUMS.index(gender) <=> VALID_ENUMS.index(other.gender)
raise InequalityError "Value of genders is not comparable"
end
def to_s
gender.to_s
end
def male?
@gender == :male
end
def female?
@gender == :female
end
def self.male
new :male
end
def self.female
new :female
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment