How can I DRY this up?

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 :frowning:

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 [email protected] wrote:

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

Ha!

Rookie error

Thanks for that Fred.

:slight_smile:

On Jul 5, 4:52 pm, Frederick C. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs