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 <craign...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> 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, 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> E.g. > > validate :foo > > def foo > bar > end > > Appears in /models/a.rb and /models/b.rb > > Can I make foo DRY? > > TIA, > Craig
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. -- Posted via http://www.ruby-forum.com/.
Hi Craig, My solution to this problem can be found here: http://gist.github.com/203225 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? -- Posted via http://www.ruby-forum.com/.
Thanks, Stephan, Ar & Lake! Ar: sorry about the sloppy use of the word "combine" -- I meant refactor :) On Oct 6, 12:36 pm, Lake Denman <rails-mailing-l...-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org> wrote:> Hi Craig, > > My solution to this problem can be found here: > > http://gist.github.com/203225 > > 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? > -- > Posted viahttp://www.ruby-forum.com/.