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

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,

  http://marklunds.com/articles/one/312

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: