-
-
Save squeedee/71083d03ae9a5ec998bc 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
# -*- encoding : utf-8 -*- | |
module BookingRequestEvent::HasOriginator | |
extend ActiveSupport::Concern | |
# you could add :crew if you needed it later | |
VALID_ORIGINATORS = { | |
:person => "Person", | |
:operator => "User" | |
} | |
module ClassMethods | |
def validate_originators(*list) | |
@originators = list | |
validate :has_one_originator | |
associate_originators | |
end | |
def originators | |
@originators ||= [] | |
end | |
private | |
def associate_originators | |
@originators.each do |originator| | |
raise "Originator not valid" unless VALID_ORIGINATORS.include?(originator) | |
belongs_to originator, :class_name => VALID_ORIGINATORS[originator] | |
end | |
end | |
end | |
def originators | |
self.class.originators | |
end | |
def originator | |
@originator ||= originators.detect { |originator| self.send(originator) != nil } | |
end | |
def originator_is_person? | |
self.originator == :person | |
end | |
def originator_is_operator? | |
self.originator == :operator | |
end | |
def has_one_originator | |
return if originators.one?() { |originator| self.send(originator) != nil } | |
if originators.length == 1 | |
errors.add(originators.first, "is the required originator") | |
else | |
errors.add(:originators, "must have one, and only one, specified") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment