# How can I DRY this up?

**URL:** <https://www.ruby-forum.com/t/how-can-i-dry-this-up/171566>\
**Category:** Rails\
**Created:** [July 5, 2009, 5:43pm UTC](https://www.ruby-forum.com/t/how-can-i-dry-this-up/171566 "2009-07-05T17:43:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![dr\_gavin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c37758/32.png) [@dr\_gavin](https://www.ruby-forum.com/u/dr_gavin)\
**Post date:** [July 5, 2009, 5:43pm UTC](https://www.ruby-forum.com/t/how-can-i-dry-this-up/171566/1 "2009-07-05T17:43:54Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![dr\_gavin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c37758/32.png) [@dr\_gavin](https://www.ruby-forum.com/u/dr_gavin)\
**Post date:** [July 5, 2009, 9:01pm UTC](https://www.ruby-forum.com/t/how-can-i-dry-this-up/171566/2 "2009-07-05T21:01:28Z")

</div>

On Jul 5, 11:42 am, Gavin [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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

---

<div class="post-metadata">

**Author:** ![dr\_gavin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c37758/32.png) [@dr\_gavin](https://www.ruby-forum.com/u/dr_gavin)\
**Post date:** [July 5, 2009, 10:20pm UTC](https://www.ruby-forum.com/t/how-can-i-dry-this-up/171566/3 "2009-07-05T22:20:54Z")

</div>

Ha!

Rookie error

Thanks for that Fred.

🙂

On Jul 5, 4:52 pm, Frederick C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
