Hi all,
I''m hoping to get some help with validates_inclusion_of. I''m
trying
to modify the method so that it accepts a symbol or Proc, so that the
list of valid values is computed dynamically at the time of
validation. However, I''m starting to think this might not even be
possible, given the way validations are implemented. It looks as
though when I pass in a proc, it is called just once and the value
stored. Can anyone advise on how modify this so that the proc is
actually called upon validation? I appreciate any tips.
This is what I have so far:
module ActiveRecord
module Validations
module ClassMethods
def validates_inclusion_of(*attr_names)
configuration = { :message =>
ActiveRecord::Errors.default_error_messages[:inclusion], :on
=> :save }
configuration.update(attr_names.extract_options!)
enum = configuration[:in] || configuration[:within]
# allow :in parameter to be a symbol or proc
if enum.is_a? Symbol then
testenum = send(enum)
elsif enum.is_a? Proc then
testenum = enum.call
else
testenum = enum
end
raise(ArgumentError, "An object with the method include? is
required must be supplied as the :in option of the configuration
hash") unless testenum.respond_to?("include?")
validates_each(attr_names, configuration) do |record,
attr_name, value|
# NPG package the value in an array if necessary
if !value.respond_to? :each then
value = [ value ] #
end
# NPG allow :in parameter to be a proc
if enum.is_a? Symbol then
enum = send(enum)
end
if enum.is_a? Proc then
enum = enum.call
end
value.each do |val| # iterate over each value in the field
record.errors.add(attr_name, configuration[:message] %
val) unless enum.include?(val)
end
end
end
end
end
end
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Core" group.
To post to this group, send email to rubyonrails-core@googlegroups.com
To unsubscribe from this group, send email to
rubyonrails-core-unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/rubyonrails-core?hl=en
-~----------~----~----~----~------~----~------~--~---