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

ruby-on-rails – 在Rails中运行另一个方法之前调用方法

发布时间:2020-12-17 02:53:53 所属栏目:百科 来源:网络整理
导读:我有一个Model,它有method_1到method_10.我也有ModelObserver. 我想在调用method1到method_9之前通知ModelObserver,而不是method_10. 是否有一种干燥的方式来编写它,而不是在所有9种方法中重复notify_observers(:after_something)? 解决方法 在config / in
我有一个Model,它有method_1到method_10.我也有ModelObserver.
我想在调用method1到method_9之前通知ModelObserver,而不是method_10.

是否有一种干燥的方式来编写它,而不是在所有9种方法中重复notify_observers(:after_something)?

解决方法

在config / initializers dirctory中添加名为monkey_patches.rb的文件.

class Object
  def self.method_hook(*args)
    options = args.extract_options!
    return unless (options[:before].present? or options[:after].present?)
    args.each do |method_name|      
      old_method = instance_method(method_name) rescue next

      define_method(method_name) do |*args|
        # invoke before callback
        if options[:before].present?
          options[:before].is_a?(Proc) ? options[:before].call(method_name,self):
            send(options[:before],method_name) 
        end

        # you can modify the code to call after callback 
        # only when the old method returns true etc..
        old_method.bind(self).call(*args)

        # invoke after callback
        if options[:after].present?
          options[:after].is_a?(Proc) ? options[:after].call(method_name,self): 
            send(options[:after],method_name) 
        end
      end
    end
  end
end

该补丁使您可以在类的实例方法上添加回调之前和之后.一个钩子可以是:

>接受一个参数的实例方法的名称
> lambda接受两个参数

可以在同一方法上注册多个挂钩.挂钩的方法应该在钩子之前.

例如:

class Model < ActiveRecord::Base

  def method1
  end

  def method2
  end

  def method3
  end

  def method4
  end

  def update_cache
  end

  # instance method name as `after` callback parameter
  method_hook :method1,:method2,:after => :update_cache

  # lambda as `before` callback parameter
  method_hook :method1,:before => lambda{|name,record| p name;p record}

  # lambda as `after` callback parameter
  method_hook :method3,:method4,:after => lambda{|name,record| 
       Model2.increment_counter(:post_count,record.model2_id)}

end

(编辑:李大同)

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

    推荐文章
      热点阅读