Keeping DRY - I like a simple life!

Hi,

I’m new to Ruby and Rails and I would be very grateful for some advice.
I’ve got the following code.

class Foo < ActiveRecord::Base

include Versionable # Some methods to handle my versioned objects

has_many :versions, :class_name => “FooVersion”, :foreign_key =>
“parent_id”
belongs_to :curr, :class_name => “FooVersion”, :foreign_key =>
“current_id”
belongs_to :unapproved, :class_name => “FooVersion”, :foreign_key =>
“unapproved_id”

end

I’d like to make use of this again with my Bar and BarVersion class
without copying and pasting. Any thoughs on how I could do this?

Thanks,

Richard

On Oct 22, 2006, at 3:19 PM, Chris W. wrote:

On Oct 22, 2006, at 2:19 PM, Rich H wrote:

I’d like to make use of this again with my Bar and BarVersion class
without copying and pasting. Any thoughs on how I could do this?

In your Versionable module:

But don’t dare forget the commas, like I did.

The correct version:

def self.included(klass)
versioned_class = klass.name + ‘Version’
klass.send(:has_many, :versions, :class_name => versioned_class,
:foreign_key =>“parent_id”)
klass.send(:belongs_to, :curr, :class_name => versioned_class,
:foreign_key => “current_id”)
klass.send(:belongs_to, :unapproved, :class_name => versioned_class,
:foreign_key => “unapproved_id”)
end


Chris W.
http://errtheblog.com

On Oct 22, 2006, at 2:19 PM, Rich H wrote:

I’d like to make use of this again with my Bar and BarVersion class
without copying and pasting. Any thoughs on how I could do this?

In your Versionable module:

def self.included(klass)
versioned_class = klass.name + ‘Version’
klass.send(:has_many, :versions, :class_name => versioned_class,
:foreign_key =>“parent_id”)
klass.send(:belongs_to :curr, :class_name => versioned_class,
:foreign_key => “current_id”)
klass.send(:belongs_to :unapproved, :class_name => versioned_class,
:foreign_key => “unapproved_id”)
end

Make sense?

http://ruby-doc.org/core/classes/Module.html#M000743


Chris W.
http://errtheblog.com

Thanks Chris.

I’ve done something similar and added it to a plugin. It works
perfectly.

Thanks again.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs