From: Robert Klemme Date: 2011-04-17T06:51:34+09:00 Subject: Re: looking for an "inversion" pattern On 16.04.2011 23:14, Brian Candler wrote: > Fearless Fool wrote in post #992929: >> I'm sure there's a clean way to do this in Ruby, but I haven't figured >> it out. >> >> I'd like to create a method +foo+ that transforms: >> >> my_obj.foo.some_method(*args) >> >> to >> >> MyClass.some_method(my_obj, *args) > > Not sure, but would bound or unbound methods help you? > > bound_method = my_obj.method(:foo) > bound_method.call(*args) > > unbound_method = my_obj.class.instance_method(:foo) > unbound_method.bind(my_obj).call(*args) You can only bind to instances of the original type. You cannot use #unbind and #bind to let a method be called on a different type. But this would be necessary for the OP's requirement to be fulfilled. irb(main):001:0> class Foo irb(main):002:1> def self.bar;123;end irb(main):003:1> end => nil irb(main):004:0> m=Foo.method(:bar).unbind => ##bar> irb(main):005:0> f=Foo.new => # irb(main):006:0> m.bind(f) TypeError: singleton method called for a different object from (irb):6:in `bind' from (irb):6 from /usr/local/bin/irb19:12:in `
' irb(main):007:0> m.bind(Foo) => # irb(main):008:0> m.bind(Foo).call => 123 Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/