Forum: Ruby on Rails validates_presence_of in a mixed-in module?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
58c6efb8466b9f85155fe6aa9fc37fce?d=identicon&s=25 Chris T (Guest)
on 2006-06-07 13:46
(Received via mailing list)
Anyone got any idea of how to use built-in validation methods in a
mixed-in module.

What I've got at the moment is each class that needs ranking methods
includes [the module] Ranking. Then the module Ranking has a bunch of
instance methods and a submodule ClassMethods. The ClassMethods in this
are mixed in to the class with self.included. So far so good.

But I want the module to contain some validation definitions (using the
built in methods validates_presence_of etc) for the classes that are
mixin it in. Have tried putting them in the ClassMethods and the
instance methods, and both throw up NoMethodError when I start up the
console.

Anyone able to help?
B100b527ce77a7706c976387493df325?d=identicon&s=25 Chris T (Guest)
on 2006-06-07 16:44
Chris T wrote:
> Anyone got any idea of how to use built-in validation methods in a
> mixed-in module.
>
> What I've got at the moment is each class that needs ranking methods
> includes [the module] Ranking. Then the module Ranking has a bunch of
> instance methods and a submodule ClassMethods. The ClassMethods in this
> are mixed in to the class with self.included. So far so good.
>
> But I want the module to contain some validation definitions (using the
> built in methods validates_presence_of etc) for the classes that are
> mixin it in. Have tried putting them in the ClassMethods and the
> instance methods, and both throw up NoMethodError when I start up the
> console.
>
> Anyone able to help?
OK. Finally got this sorted. Here's how I did it for future reference
(with many thanks to the excellent Ruby For Railsbook).
validates_presence_of and the other validates methods, along with
attr_protected, which I was also trying to mix in are class methods.
Normally when defining them in a class (model) definition, the self is
implicit (i.e. validates_presence_of is interpreted as
self.validates_presence_of). However, in the self.included(klass) you
need to make the receiver explicit.

So:
def self.included(klass)
  klass.validates_presence_of :ranking
  klass.attr_protected :ranking
end

At least this works for me. If there are any rails gurus out there who
can point out a better way do chip in.
This topic is locked and can not be replied to.