Hey all! Hope you''re having a good weekend. I have a couple of models that share a lot of similar validation so I figured this would be a good opportunity to DRY my code up. lets say for example: class Squirrel < ActiveRecode::Base validates_presence_of :name end class Badger < ActiveRecode::Base validates_presence_of :name end what I''ve been trying to do is add a module in /lib called CommonValidations module CommonValidations def included(base) base.class_eval do validates_presence_of :name end end end and then include this module in the models that require it. I''ve also tried various combinations with ''eval'' and ''send'' etc. The validations aren''t called :( Can anyone explain why this isn''t working and if it''s possbile to re- use validations like this? Thanks Gavin
On Jul 5, 11:42 am, Gavin <ga...-YMj/zd8x6QpKMzDMP321V2ksYUyLi9NM@public.gmane.org> wrote:> module CommonValidations > > def included(base) > base.class_eval do > validates_presence_of :name > end > end > end > > and then include this module in the models that require it. I''ve also > tried various combinations with ''eval'' and ''send'' etc.Did you check to see whether your included method is called at all ? The included method needs to be a module method, i.e. def self.included(base) ... end for it to be used the way you want it to be used. Fred> > The validations aren''t called :( > > Can anyone explain why this isn''t working and if it''s possbile to re- > use validations like this? > > Thanks > > Gavin
Ha! Rookie error Thanks for that Fred. :) On Jul 5, 4:52 pm, Frederick Cheung <frederick.che...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> On Jul 5, 11:42 am, Gavin <ga...-YMj/zd8x6QpKMzDMP321V2ksYUyLi9NM@public.gmane.org> wrote: > > > module CommonValidations > > > def included(base) > > base.class_eval do > > validates_presence_of :name > > end > > end > > end > > > and then include this module in the models that require it. I''ve also > > tried various combinations with ''eval'' and ''send'' etc. > > Did you check to see whether your included method is called at all ? > The included method needs to be a module method, i.e. > > def self.included(base) > ... > end > > for it to be used the way you want it to be used. > > Fred > > > > > The validations aren''t called :( > > > Can anyone explain why this isn''t working and if it''s possbile to re- > > use validations like this? > > > Thanks > > > Gavin > >