Hook methods are similar to event-driven devices that can perform a specific callback function after a particular event occurs, which is the hook method (more descriptive: The hook method can hook a particular event like a hook). , the Before\after function is the most common hook method in rails.
The Class#inherited method is also a hook method that Ruby invokes when a class is inherited. By default, class#inherited does nothing, but by inheriting, we can intercept the event and respond to the inherited events of interest.
Class String
def self.inherited (subclass)
puts "#{self} is inherited by #{subclass}"
End
Class MyString < String; End
Output:
String is inherited by MyString
By using the Hook method, you can allow us to intervene in the lifecycle of a Ruby class or module, which can greatly improve the flexibility of programming.
Add an instance of a hook to a method call
Ruby has a lot of useful hooks, such as included,inhered, and method_missing. Adding hooks to method calls can be implemented with alias wrapping, but after all, alias_method_chain need to define with_feature methods is also more cumbersome, so the following module,include are invoked Method_ Callback:before_method,:after_method can add After_method hooks for Before_method
Module Aftercall
def self.included (base)
base.extend (classmethods)
end
module Classmethods
def after_call when_call,then_call,*args_then,&block_then
alias_method "Old_#{when_call}", When_call
Define_method When_call do |*args_when,&block_when|
Send "Old_#{when_call}", *args_when,&block_when
send Then_call,*args_then,&block_then end
End
End
class Student
include Aftercall
def enter_class sb
puts "Enter class #{sb}"
yield (' before ') if Block_given?
End
private
def after_enter_class pops
puts "after Enter class #{pop}"
yield (' after ') if Block_ Given?
End
protected
def third_after
puts ' from third enter '
end
After_call:after_enter_class: Third_after
After_call:enter_class,: After_enter_class, "Doubi", &lambda {|x|puts "from Lambda #{x}"}
End
Student.new.enter_class "1" Do |x|
Puts ' from Lambda #{x} ' end
The results of the operation are as follows:
#enter Class 1
#from lambda before
#after Enter class Doubi
#from Lambda after
#from third enter