2014-04-21 35 views
0

我想知道是否有可能在运行时使用自定义回调代码在Rails中赋予模型?Rails:运行时自定义回调?

我有一个情况,我有很多“节点”正在创建“事件”,并且每个节点可能需要在事件上运行特定的回调。例如,一个节点在创建事件之前可能需要向第三方API发出额外数据。创建事件后,另一个节点可能需要向其所有者发送电子邮件。

在我的头上,这是有道理设立这样的事情时,我做了一个“POST /节点/ 4 /事件”:

class Nodes::EventsController < ApplicationController 
    def create 

    # ...security checks in place and we have a @node 

    if @node.requires_custom_callbacks? 
     # Load the file with callbacks for @node.id, 
     # something like Node4EventExtensions 
     # Apply Node4EventExtensions to the Event model 
    end 

    Event.create 

    end 
end 

这将保持特定节点的代码我的事件模型,并允许我分别构建/测试自定义节点扩展。这是否有可能在Rails中脱颖而出?我还有另外一种方式来看待这个吗?

+0

你想描述一个工作流引擎吗? –

+0

我不得不查找工作流引擎。我不认为这正是我正在寻找的。我的一些节点在发布活动时有特定的自定义要求。 Node20可能需要一个before_create回调来ping第三方API以获得许可,而Node22可能需要after_create才能在成功时发送电子邮件。 我的想法是,我可以创建类似“Node20Event”模块的东西,并将其动态地包含到Event中,以便Event在请求期间的行为与Node20Event类似。我还没有找到办法解决这个问题。 –

+0

那么你可能需要创建你的模型的子类。 –

回答

0

我已经完成了这种方式,它似乎在等待我的初始自定义要求。下面是它是如何连接的一个精简版:

我的控制器调用事件类方法:然后

class Nodes::EventsController < ApplicationController 
    def create 

    # ...security checks in place and we have a @node 

    if @node.requires_custom_callbacks? 
     Event.extend_for_node(node.id) 
    end 
    Event.create 
    end 
end 

事件模型包括该节点模块:

class Event < ActiveRecord::Base 

    def self.extend_for_node(node_id) 
    include "#Node{node_id}Event".constantize 
    end 

    ... 

end 

模块将包含额外的要求:

module Node20Event extend ActiveSupport::Concern 

    included do 
    before_create :im_here 
    end 

    def im_here 
    throw "HERE" 
    end 

end