2014-07-03 81 views
0

我的任务是为Rails应用程序(Foreman)实现一个非常基本的功能请求,并且偶然发现了一个似乎既非常基本又非常流行的问题。从Java背景来看,我发现回调不像我通常所期望的那样工作。Ruby on Rails - 回调

通常在Java中使用侦听器时,可以为事件订阅任意代码片段,并且当事件触发时,对象遍历侦听器并通知每个侦听器。一个非常简单的例子是:

public class Foo { 
    private List<FooListener> foo_list = new List<FooListener>(); 
    public void add_foo_listener(FooListener fooListener){ 
     this.foo_list.add(fooListener); 
    } 
    private void on_foo_thing(){ 
     foreach(foo : foo_list) { 
      fooListener.notify(); 
     } 
    } 
} 

所以,你可以通过调用“add_foo_listener(FooListener的)”的时候,on_foo_thing()方法被调用,将被通知增加从外部类然而,许多听众 - 无需任何修改原创课。

ruby​​/rails中是否有类似的东西?我想勾入类具有以下挂钩定义:

define_model_callbacks :build, :only => :after 
define_model_callbacks :provision, :only => :before 

# Custom hooks will be executed after_commit 
after_commit :build_hooks, :if => :persisted? 

def build_hooks 
    return unless respond_to?(:old) && old && (build? != old.build?) 
    if build? 
     run_callbacks :build do 
     logger.debug { "custom hook after_build on #{name} will be executed if defined." } 
     end 
    else 
     run_callbacks :provision do 
     logger.debug { "custom hook before_provision on #{name} will be executed if defined." } 
     end 
    end 
    end 
+0

可能重复[我怎样使用Ruby元编程将回调添加到Rails模型?](http://stackoverflow.com/questions/12084234/how-do-i-use-ruby-metaprogramming-to-add-callbacks-to-a-rails-model ) – Benj

+0

如果我错了,请纠正我,但从我对ActiveSupport :: Concern的理解中,我将不得不编辑原始类定义以包含我的关注类,这个答案似乎可以重新执行。 – HeWhoWas

回答

0

虽然可能重复的是正确的,为了改变轨道模型无需编辑该模型的代码,明确列入听了,你使用以下:

Host::Managed.send(:include, ::HostExtensions::ManagedHost) 

这是告诉主持人::托管类,它应该包括HostExtensions ::在运行时ManagedHost的模块。

而对完整性的考虑,如果你在一个Rails应用程序这样做,你可能需要像这样添加到您的引擎类(engine.rb)的

config.to_prepare do 
    require File.expand_path('../../../app/models/concerns/host_extensions/managedhost', __FILE__) 
    Host::Managed.send(:include, ::HostExtensions::ManagedHost) 
end