2017年8月22日 星期二

Metaprograming 做 after method callback

Magic


```ruby
class Example
  def self.after(*names)
    names.each do |name|
      m = instance_method(name.to_s)
      # override old method
      define_method(name.to_s) do |*args, &block|
        m.bind(self).(*args, &block) # 這裡執行了 test method
        yield(self, name.to_sym, *args) # 這裡才是真正 callback 發生的地方
        self
      end
    end
  end

  def test(arg1, options)
    # do someting...
    # self => instance of Example
  end

  after(:test) do |example_instance, test_hash, arg1, options|
    #example_instance => instance of Example, self, from test method
    #test_hash => :test
  end
end
```

https://ruby-doc.org/core-2.2.0/UnboundMethod.html#method-i-bind

沒有留言:

張貼留言