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.
--
Posted via http://www.ruby-forum.com/.