国产探花免费观看_亚洲丰满少妇自慰呻吟_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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 永德县| 隆林| 洪洞县| 河源市| 瑞金市| 北京市| 利川市| 盘锦市| 麻江县| 香河县| 江津市| 雷波县| 平南县| 丁青县| 纳雍县| 明光市| 崇文区| 铜梁县| 右玉县| 荃湾区| 江北区| 铁岭县| 曲靖市| 涟水县| 六安市| 务川| 孟津县| 余庆县| 理塘县| 金华市| 大关县| 郯城县| 佛山市| 内江市| 新宁县| 屯留县| 吕梁市| 正镶白旗| 宣威市| 清新县| 错那县|