2013-09-16 53 views
1

我在一个类中有几个函数。对于每个函数,我希望能够指定在执行之前应该调用什么,以及执行它之后要调用什么。如何在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连接。我已经编写了大部分函数,​​因此只需声明两个函数,一个用于打开连接,另一个用于关闭连接。

+1

将你的方法包装成块 – apneadiving

回答

1

你可以通过define_methodalias_method_chain,一些使用一些红宝石元编程像这样也许:

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

以上(未经测试)代码:

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) 

然后在任意类中使用它演示了挂钩实例方法的想法,但如果需要,还可以适应类方法。

相关问题