国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

實例講解Ruby中的鉤子方法及對方法調用添加鉤子

2019-10-26 19:29:35
字體:
來源:轉載
供稿:網友

鉤子方法有些類似事件驅動裝置,可以在特定的事件發生后執行特定的回調函數,這個回調函數就是鉤子方法(更形象的描述: 鉤子方法可以像鉤子一樣,勾住一個特定的事件。),在Rails中before/after函數就是最常見的鉤子方法。

Class#inherited方法也是這樣一個鉤子方法,當一個類被繼承時,Ruby會調用該方法。默認情況下,Class#inherited什么都不做,但是通過繼承,我們可以攔截該事件,對感興趣的繼承事件作出回應。

class String  def self.inherited(subclass)    puts “#{self} was inherited by #{subclass}”  endendclass 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 endendclass 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}"}endStudent.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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 德化县| 开远市| 新昌县| 中方县| 台前县| 灵丘县| 正镶白旗| 宜兴市| 宿迁市| 阿拉善右旗| 沂水县| 赤城县| 临湘市| 大名县| 枣阳市| 西乡县| 昌平区| 绥化市| 安岳县| 萨嘎县| 九寨沟县| 重庆市| 凉城县| 明光市| 青神县| 闵行区| 临夏市| 色达县| 南涧| 赣州市| 宜宾市| 调兵山市| 台安县| 咸宁市| 旬阳县| 永泰县| 昭通市| 读书| 凤山县| 台前县| 阜新|