DRY model validation question

Here’s a question:

I have the exact same validation code in 2 different models.

OK, you’re thinking, combine the models. Not in this case.

So, in Rails, is there a way to reference the same validation for 2
different models?

E.g.

validate :foo

def foo
bar
end

Appears in /models/a.rb and /models/b.rb

Can I make foo DRY?

TIA,
Craig

On Oct 5, 4:42 pm, Dudebot [email protected] wrote:

Here’s a question:

I have the exact same validation code in 2 different models.

OK, you’re thinking, combine the models. Not in this case.

So, in Rails, is there a way to reference the same validation for 2
different models?

Commonly you can find this done with validation plugins.

See for example,

Peter Marklund's Home

for an email address validation, which is then available in all
ActiveRecord models through

class A < ActiveRecord::Base

validates_as_email :email_address

end

Stephan

Dudebot wrote:

Here’s a question:

I have the exact same validation code in 2 different models.

OK, you’re thinking, combine the models.

That shouldn’t ever be your first reaction. First reaction is to
refactor out the commonalities.

If either, or both models end up as skeletons, then you should rethink
your original design… why were they separate in the first place?
Lack of analysis. or alot of analysis that you’ve forgotten that tiny
important bit form which led you to separate them in the first place.

So, in Rails, is there a way to reference the same validation for 2
different models?

As mentioned previously, plugins, or a parent abstract class depending
on the breadth of commonalities.

Thanks, Stephan, Ar & Lake! Ar: sorry about the sloppy use of the
word “combine” – I meant refactor :slight_smile:

On Oct 6, 12:36 pm, Lake D. [email protected]

Hi Craig,

My solution to this problem can be found here:

Basically, I just add the validations in a module as instance methods
(def foo…), include that module in the models, and as the module is
included, tell the “klass” to validate the instance methods.

Make sense?