Quantcast

Ruby on Rails, Io, Lisp, JavaScript, Dynamic Languages, Prototype-based programming and more...

Technoblog reader special: $10 off web hosting by FatCow!

Thursday, June 08, 2006

Symlinking ActiveRecord Objects

Have you ever needed one object to act like another one? To symlink an object? In Rails it is quite easy to accomplish. Simply add a symlink_id integer field to your database table and use the following code.
class SomeObject < ActiveRecord::Base
def id
return symlink_id? ? super : symlink_id
end

def symlink(obj)
update_attribute :symlink_id, obj.id
end
end

There are many uses for this idea, but unfortunately I can’t reveal my use at the moment. Feel free to post comments with ideas though.

A notable limit to this code is that you can’t symlink objects that aren’t also SomeObject. It is possible to accomplish this as well however. In addition to symlink_id, add a varchar symlink_kind.
class SomeObject < ActiveRecord::Base
class << self
def find(*args)
obj = super(*args)
if obj.is_a? Array
obj.map{|o| o.symlink_kind? && o.symlink_id? ? eval(o.symlink_kind+'.find('+o.symlink_id+')') : o }
else
obj.symlink_kind? ? eval(obj.symlink_kind+'.find('+obj.symlink_id+')') : obj
end
end
end

def symlink(obj)
self.symlink_id = obj.id
self.symlink_kind = obj.class.to_s
save
end
end

You should follow me on twitter here.

Technoblog reader special: click here to get $10 off web hosting by FatCow!

1 Comments:

Anonymous Small Business Hosting said...

I wish this worked with people!

6:19 AM, October 01, 2006

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home

 

If you like this blog, you might also like top photography schools.