Is there a way for objects to pass along methods that can be shared automatically?
I seem to come into alot of circumstances where when I refactor a class, I开发者_运维百科 am often creating several methods that do nothing but pass along the information to the new (for now) subordinate class. So say I have Obj1 and it has 15 methods, and I end up moving 4 into Obj2. Now I have 4 methods in Obj1 that are just:
def foo arg1, arg2
@obj2.foo arg1, arg2
end
def bar arg1
@obj2.bar arg1
end
I would think there could be a one line way to give access to these methods that are one level removed. Like:
foo, bar = @obj2.foo, @object2.bar
or
@obj2.release(:foo, :bar)`
It would have to pass along all method arguments of course. It looks like this is a concept in python called a descriptor, but I don't see anything equivalent in Ruby.. is there?
If you're using Rails (you tagged it) you can use the delegate method:
class Widget
delegate :foo, :bar, :to => '@obj2'
end
Then calling the foo method on an instance of Widget will just call it on whatever @obj2 is.
精彩评论