Skip to content

Instantly share code, notes, and snippets.

@pacoguzman
Created May 13, 2011 15:06
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 pacoguzman/970696 to your computer and use it in GitHub Desktop.
Save pacoguzman/970696 to your computer and use it in GitHub Desktop.
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