Created
May 13, 2011 15:06
-
-
Save pacoguzman/970696 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
class DynamicInclusionValidator < ActiveModel::EachValidator | |
def check_validity! | |
raise ArgumentError, "A proc which result has the method include? is required as the " << | |
":in option of the configuration hash" unless options[:in].respond_to?(:call) | |
end | |
def validate_each(record, attribute, value) | |
unless options[:in].bind(record).call.include?(value) | |
record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value)) | |
end | |
end | |
end | |
# Usage | |
class Ranking < ActiveRecord::Base | |
RANKING_TYPES = { | |
:official => 0, | |
:public => 1, | |
:private => 2, | |
} | |
belongs_to :user | |
validates :ranking_type, :dynamic_inclusion => {:in => Proc.new{ user.present? ? user.ranking_types.values : Ranking::RANKING_TYPES.values} } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment