Adding custom validations to active record

Hi - I want to add my own validation to a rails app, and need help
making it global to my app. Basically, the validation makes sure a
number is positive - I found this code on the at
http://snippets.dzone.com/posts/show/822:

module CustomValidations

def validates_positive_or_zero(*attr_names)
configuration = { :message => “Cannot be negative” }
configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
validates_each attr_names do |m, a, v|
m.errors.add(a, configuration[:message]) if v<0
end
end

end

I want to use it in my models like any other validation:

class SomeModel < ActiveRecord::Base
validates_positivity_of :some_number, :another_number
end

I saved it in lib/custom_validations.rb, and tried including it in the
top of my environment.rb to extend AR:

include ‘custom_validations’
class ActiveRecord::Base
include CustomValidations
end

#… rest of file

Sadly, this won’t work. How do I make rails identify this module and use
it properly?

sa 125 wrote:

Sadly, this won’t work.
Always include even a snip of the error message you got. After your
detailed
writeup, just claiming “won’t work” leaves us bereft of closure!

However, the top of environment.rb might be before “require
‘active_record’”.
That means ‘class’ would introduce ‘ActiveRecord’, leaving ‘Base’ as a
missing
identifier. If so, move it to the bottom!


Phlip

my bad. I moved that block to the bottom of the environment.rb file,
after the “end” of the Rails::Initializer code, but got this error:

NoMethodError (undefined method ‘validates_positivity_of’ for
#<Class…>)
/…/active_record/base.rb:1833:in ‘method missing’

I tried loading this method though ./script/console:
irb> include CustomValidations
irb> validates_positivity_of 2
NoMethodError: undefined method ‘validates_each’ for #<object…>
from /…/lib/custom_validations.rb:6:in ‘validates_positivity_of’

Now I’m not even sure if the function works properly.

It isnt include in your case, its extend:

include ‘custom_validations’
class ActiveRecord::Base
extend CustomValidations
end

Here’s a better explanation why →
http://blog.codevader.com/2008/09/27/including-and-extending-modules-in-ruby/

Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)

On Sun, Feb 22, 2009 at 6:24 AM, sa 125