Last active
August 14, 2018 13:50
-
-
Save krisleech/70a5761e4f2c078d090d4aa8a6aa04a4 to your computer and use it in GitHub Desktop.
ActiveRecord value object
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 OrganisationCode | |
attr_reader :prefix, :suffix | |
def initialize(code) | |
@code = code | |
@prefix, @suffix = @code.split('@') | |
end | |
def to_s(format = :short) | |
case format | |
when :short | |
@prefix | |
when :long | |
@code | |
else | |
raise ArgumentError, '...' | |
end | |
end | |
end | |
class Site < AR::Base | |
def organisation_code | |
@organisation_code ||= OrganisationCode.new(super) | |
end | |
def organisation_code=(new_code) | |
@organisation_code = nil | |
super(new_code) | |
end | |
end | |
Site.create(organisation_code: 'abc@123') # => TypeError: can't quote OrganisationCode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment