Module: Hook
- Included in:
- Fastdfs::Client::Storage, Fastdfs::Client::Tracker
- Defined in:
- lib/fastdfs-client/hook.rb
Instance Method Summary collapse
- #add_hook(where, meth_name, &callback) ⇒ Object
- #after(*meth_names, &callback) ⇒ Object
- #before(*meth_names, &callback) ⇒ Object
- #ensure_hijacked(meth_name) ⇒ Object
- #hooks ⇒ Object
- #method_added(meth_name) ⇒ Object
Instance Method Details
#add_hook(where, meth_name, &callback) ⇒ Object
16 17 18 19 |
# File 'lib/fastdfs-client/hook.rb', line 16 def add_hook(where, meth_name, &callback) hooks[meth_name][where] << callback ensure_hijacked meth_name end |
#after(*meth_names, &callback) ⇒ Object
6 7 8 |
# File 'lib/fastdfs-client/hook.rb', line 6 def after(*meth_names, &callback) meth_names.each{|meth_name| add_hook :after, meth_name, &callback } end |
#before(*meth_names, &callback) ⇒ Object
2 3 4 |
# File 'lib/fastdfs-client/hook.rb', line 2 def before(*meth_names, &callback) meth_names.each{|meth_name| add_hook :before, meth_name, &callback } end |
#ensure_hijacked(meth_name) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/fastdfs-client/hook.rb', line 25 def ensure_hijacked(meth_name) return if hooks[meth_name][:hijacked] || !instance_methods.include?(meth_name) meth = instance_method meth_name _hooks = hooks _hooks[meth_name][:hijacked] = true define_method meth_name do |*args, &block| _hooks[meth_name][:before].each do |callback| self.instance_exec(&callback) end return_value = meth.bind(self).call *args, &block _hooks[meth_name][:after].each do |callback| self.instance_exec(&callback) end return_value end end |
#hooks ⇒ Object
10 11 12 13 14 |
# File 'lib/fastdfs-client/hook.rb', line 10 def hooks @hooks ||= Hash.new do |hash, method_name| hash[method_name] = { before: [], after: [], hijacked: false } end end |
#method_added(meth_name) ⇒ Object
21 22 23 |
# File 'lib/fastdfs-client/hook.rb', line 21 def method_added(meth_name) ensure_hijacked meth_name if hooks.has_key? meth_name end |