Rails: keeping DRY with ActiveRecord models that share similar complex attributes
Posted
by Greg
on Stack Overflow
See other posts from Stack Overflow
or by Greg
Published on 2010-05-20T00:12:32Z
Indexed on
2010/05/20
0:20 UTC
Read the original article
Hit count: 528
This seems like it should have a straightforward answer, but after much time on Google and SO I can't find it. It might be a case of missing the right keywords.
In my RoR application I have several models that share a specific kind of string attribute that has special validation and other functionality. The closest similar example I can think of is a string that represents a URL.
This leads to a lot of duplication in the models (and even more duplication in the unit tests), but I'm not sure how to make it more DRY.
I can think of several possible directions...
- create a plugin along the lines of the "validates_url_format_of" plugin, but that would only make the validations DRY
- give this special string its own model, but this seems like a very heavy solution
- create a ruby class for this special string, but how do I get ActiveRecord to associate this class with the model attribute that is a string in the db
Number 3 seems the most reasonable, but I can't figure out how to extend ActiveRecord to handle anything other than the base data types. Any pointers?
Finally, if there is a way to do this, where in the folder hierarchy would you put the new class that is not a model?
Many thanks.
© Stack Overflow or respective owner