Skip to content

Instantly share code, notes, and snippets.

@bogdan
Created September 21, 2020 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bogdan/35aa76756b3d0e082bcd28151370eab6 to your computer and use it in GitHub Desktop.
Save bogdan/35aa76756b3d0e082bcd28151370eab6 to your computer and use it in GitHub Desktop.
class TransitionValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return unless record.changes[attribute]
transitions = options
start = record.send(:"#{attribute}_was")
destination = value
message = options[:message] || "can not be transitioned from #{start.inspect} to #{destination.inspect}"
allowed_transitions = transitions[start]
unless allowed_transitions
raise Error, record.errors.full_message(attribute, message)
end
unless Array(allowed_transitions).map(&:to_sym).include?(destination.to_sym)
raise Error, record.errors.full_message(attribute, message)
end
end
class Error < StandardError
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment