-
-
Save blahutka/49648c4bcf3ae1ce82ddeafa8fda9f1e to your computer and use it in GitHub Desktop.
Declarative AM validations depending on arbitrary attributes
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 Page | |
# include ValidationsFor | |
# | |
# validations_for page_type: 'offer' do | |
# validates :amount, presence: true | |
# end | |
# | |
# validations_for page_type: 'page' do | |
# validates :title, presence: true | |
# end | |
# end | |
module ValidationsFor | |
extend ActiveSupport::Concern | |
class ValidatorWrapper < SimpleDelegator | |
include ActiveModel::Validations | |
def self.model_name | |
ActiveModel::Name.new(ValidatorWrapper) | |
end | |
end | |
included do | |
mattr_accessor :_validation_spec | |
validate do |record| | |
spec = self._validation_spec || [] | |
spec.each do |(attrs, wrapper)| | |
if attrs.all?{ |k, v| record[k] == v } | |
validator = wrapper.new(record) | |
if !validator.valid? | |
validator.errors.each do |k, msg| | |
record.errors.add(k, msg) | |
end | |
end | |
end | |
end | |
end | |
end | |
class_methods do | |
def validations_for(attrs, &block) | |
wrapper = Class.new(ValidatorWrapper, &block) | |
self._validation_spec ||= [] | |
self._validation_spec << [attrs, wrapper] | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment