如何在 Rails 中回调前后添加泛型



我在一个类中有几个函数。对于每个函数,我希望能够在执行之前指定应该调用任何内容,以及在执行之后调用任何内容。

例如,假设我的函数是 a、b、c、d 和 e。我想做如下事情:

before: [:a, :b, :c], execute: :before_func
after: [d, e], execute: :after_func

是否有宝石或技术可用于完成上述任务?

背景:

我的类基本上是一个从ftp读取文件的类。我已经声明了一个@ftp变量,该变量在创建类实例时初始化,然后在需要时尝试从ftp读取,或在ftp上执行其他操作。现在,如果操作发生得很近,它可以工作,但否则它会超时。因此,在每个函数之前,我想关闭当前@ftp,然后重新打开一个新连接并使用它。当函数结束时,我想关闭FTP连接。我已经编写了大多数函数,所以只想声明两个函数,一个用于打开连接,一个用于关闭连接。

您可以通过 define_methodalias_method_chain 使用一些 ruby 元编程,也许是这样的:

module MethodHooks
  def before(*symbols)
    hook=symbols.pop
    symbols.each { |meth|
      define_method :"#{meth}_with_before_#{hook}" do |*args, &block|
        self.send hook, *args, &block
        self.send :"#{meth}_without_before_#{hook}", *args, &block
      end
      alias_method_chain meth, :"before_#{hook}"
    }
  end
  def after(*symbols)
    hook=symbols.pop
    symbols.each { |meth|
      define_method :"#{meth}_with_after_#{hook}" do |*args, &block|
        self.send :"#{meth}_without_after_#{hook}", *args, &block
        self.send hook, *args, &block
      end
      alias_method_chain meth, :"after_#{hook}"
    }
  end
end
Object.extend(MethodHooks)

然后在任意类中使用它:

before :a, :b, :c, :before_func
after :a, :b, :c, :after_func

上面(未经测试的)代码演示了挂钩实例方法的想法,但如果需要,您也可以适应类方法。

本质上,你正在寻找在Rails中进行面向方面的编程。

也许这颗宝石可能会帮助 https://github.com/davesims/simple-aop

最新更新