相思资源网 Design By www.200059.com
钩子方法有些类似事件驱动装置,可以在特定的事件发生后执行特定的回调函数,这个回调函数就是钩子方法(更形象的描述: 钩子方法可以像钩子一样,勾住一个特定的事件。),在Rails中before\after函数就是最常见的钩子方法。
Class#inherited方法也是这样一个钩子方法,当一个类被继承时,Ruby会调用该方法。默认情况下,Class#inherited什么都不做,但是通过继承,我们可以拦截该事件,对感兴趣的继承事件作出回应。
class String def self.inherited(subclass) puts “#{self} was inherited by #{subclass}” end end class MyString < String; end
String was inherited by MyString
通过使用钩子方法,可以让我们在Ruby的类或模块的生命周期中进行干预,可以极大的提高编程的灵活性。
对方法调用添加钩子的实例
ruby有很多有用的钩子,如included,inhered,以及method_missing。对方法调用添加钩子可以用alias环绕别名实现,但终归有些麻烦,alias_method_chain需要定义with_feature方法也较麻烦,因此实现了下列module,include后调用method_callback :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"after enter class #{pop}" yield('after') if block_given"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
标签:
Ruby,方法,钩子
相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com
暂无实例讲解Ruby中的钩子方法及对方法调用添加钩子的评论...
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。