如何在rails中回调之前和之后添加泛型

时间:2013-09-16 14:25:11

标签: ruby-on-rails ruby

我在课堂上有一些功能。对于每个函数,我希望能够指定在执行它之前应该调用什么,以及在执行它之后要调用的内容。

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

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

我可以使用宝石或技术来完成上述工作吗?

背景:

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

2 个答案:

答案 0 :(得分:1)

你可以通过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

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

答案 1 :(得分:0)

基本上,您希望在Rails中进行面向方面编程。

也许这个宝石可以帮助https://github.com/davesims/simple-aop