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
endThere 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
1 Comments:
I wish this worked with people!
6:19 AM, October 01, 2006
Post a Comment
<< Home