位置:首页 > Ruby > Ruby钩子方法实例讲解:为方法调用添加钩子

Ruby钩子方法实例讲解:为方法调用添加钩子

时间:2026-08-18  |  作者:电竞小硕  |  阅读:0

钩子方法的概念,其实和事件驱动机制很像——一旦某个特定事件被触发,系统就会自动执行对应的回调函数。这个回调函数就是所谓的“钩子”。更形象地说,它就像一把钩子,精准地勾住你感兴趣的那个事件。在 Rails 框架里,before_actionafter_action 这类方法就是最常见的钩子。

实例讲解Ruby中的钩子方法及对方法调用添加钩子

除了 before/after 这类显式挂钩,Ruby 还提供了 Class#inherited 这个隐式钩子。当一个类被继承时,Ruby 会自动调用这个方法。默认情况下它什么也不做,但你可以覆盖它,在继承发生时插入自己的逻辑——相当于精准拦截了一次类继承事件。

class String
  def self.inherited(subclass)
    puts “#{self} was inherited by #{subclass}”
  end
end
class MyString < String; end
输出:
String was inherited by MyString

借助这些钩子方法,你就能在类或模块的生命周期中自由插桩,灵活度瞬间拉满。

对方法调用添加钩子的实例

Ruby 本身已经提供了不少内置钩子,比如 includedinherited,还有 method_missing。要在方法调用时额外设上钩子,传统做法是用 alias 别名环绕,但写起来有点啰嗦;alias_method_chain 则需要先定义一个 with_feature 方法,也挺麻烦。下面这段代码实现了一个 AfterCall 模块,只要 include 进去,再调用 after_call :before_method, :after_method,就能给 before_method 后面自动挂上 after_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
end
class Student
 include AfterCall
 def enter_class sb
  puts "enter class #{sb}"
  yield('before') if block_given?
 end
 private
 def after_enter_class pop
  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

运行结果如下:

#enter class 1
#from lambda before
#after enter class doubi
#from lambda after
#from third enter

免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。

相关文章

更多

精选合集

更多

大家都在玩

热门话题

大家都在看

更多