加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在ruby中拦截方法调用?

发布时间:2020-12-16 23:02:55 所属栏目:百科 来源:网络整理
导读:我目前有一个超类,它有一个功能,我希望所有的子类在它的每个功能内调用.该函数应该在rails中表现得像一个before_filter函数,但我不知道如何执行before_filter.这是一个例子 class Superclass def before_each_method puts "Before Method" #this is supposed
我目前有一个超类,它有一个功能,我希望所有的子类在它的每个功能内调用.该函数应该在rails中表现得像一个before_filter函数,但我不知道如何执行before_filter.这是一个例子
class Superclass
  def before_each_method
    puts "Before Method" #this is supposed to be invoked by each extending class' method
  end
end

class Subclass < Superclass
  def my_method
    #when this method is called,before_each_method method is supposed to get invoked
  end
end

解决方法

这是一种方法:
class Superclass
  def before_each_method name
    p [:before_method,name]
  end

  def self.method_added name
    return if @__last_methods_added && @__last_methods_added.include?(name)
    with = :"#{name}_with_before_each_method"
    without = :"#{name}_without_before_each_method"
    @__last_methods_added = [name,with,without]
    define_method with do |*args,&block|
      before_each_method name
      send without,*args,&block
    end
    alias_method without,name
    alias_method name,with
    @__last_methods_added = nil
  end
end

class SubclassA < Superclass
  def my_new_method
    p :my_new_method
  end

  def my_new_other_method
    p :my_new_other_method
  end
end

SubclassA.new.my_new_method
SubclassA.new.my_new_other_method

一旦在子类中定义要包装的方法,这将使用alias_method_chaining方法创建一个包装方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读