Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - Pass a parameter to custom validation method

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?

like image 651
Serodis Avatar asked Dec 13 '22 12:12

Serodis


1 Answers

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!

like image 160
Serodis Avatar answered Jan 14 '23 15:01

Serodis