开发者

Rails 3 - Pass a parameter to custom validation method

开发者 https://www.devze.com 2023-03-08 21:00 出处:网络
I am looking to pass a value to a custom validation. I have done the following as a test: validate :print_out, :parameter1 => \'Hello\'

I am looking to pass a value to a custom validation. I have done the following as a test:

validate :print_out, :parameter1 => 'Hello'

With this:

def print_out (input="blank")
  puts input
end

When creating an object or saving an object, the output is 'blank.' However, if called directly:

object.print_out "Test"

Test is instead outputted. The question is, why is my parameter not开发者_开发百科 passing properly?


Inside the 'config\initializers\' directory, you can create your own validations. As an example, let's create a validation 'validates_obj_length.' Not a very useful validation, but an acceptable example:

Create the file 'obj_length_validator.rb' within the 'config\intializers\' directory.

ActiveRecord::Base.class_eval do
    def self.validates_obj_length(*attr_names)
        options = attr_names.extract_options!
        validates_each(attr_names, options) do |record, attribute, value|
          record.errors[attribute] << "Error: Length must be " + options[:length].to_s unless value.length == options[:length]
        end
    end
end

Once you have this, you can use the very clean:

validates_obj_length :content, :length => 5

Basically, we reopen ActiveRecord::Base class and implement a new sub-validation. We use the splat (*) operator to accept an array of arguments. We then extract out the hash of options into our 'options' variable. Finally we implement our validation(s). This allows the validation to be used with any model anytime and stay DRY!


You could try

validate do |object_name|
  object_name.print_out "Hello"
end

Instead of your validate :print_out, :parameter1 => 'Hello'.

0

精彩评论

暂无评论...
验证码 换一张
取 消