在插件中的过滤器之前运行。还有其他办法吗?
我正在编写我的第一个插件,在该插件中,我需要为某些控制器/操作对运行一个方法。对于这个插件,配置 yml 看起来像这样 -
track1:
start_action: "home", "index"
end_action: "user", "create"
所以,在我的插件中,我将首先阅读上面的 yml 文件。之后,我想运行一个操作,比如 -first_function 作为 before_filter 到 home-controller 索引操作,并且我将运行 secondary_function 作为 after_filter 用于用户控制器创建操作。
但我不知道如何为此编写过滤器,该过滤器将在插件中声明,并将针对用户在上述 yml 文件中指定的操作运行。
请帮忙!
I am writing my first plugin, and in that plugin, I need to run a method for some controller/action pairs. For this plugin the configuration yml looks like this -
track1:
start_action: "home", "index"
end_action: "user", "create"
So, in my plugin I will first read above yml file. After that I want to run an action say - first_function as before_filter to home-controller index-action and I would be running second_function as after_filter for user-controller create-action.
But I couldn't figure out how can I write filters for this, which will be declared in plugin and will run for actions specified by user in above yml files.
Please help !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我看到有两种选择可以实现您的目标。
第一种方法:在
ApplicationController
内声明过滤器,并在过滤器内检查controller_name
和action_name
是否与 yaml 配置中的任何内容匹配。如果匹配则执行,如果不匹配则忽略。在代码中
我希望你能明白。
第二种方法:定义
before_filter
的一种简洁方法是在模块中定义它们。通常您会使用 self.included 方法来定义 before_filter ,但当然,您可以有条件地定义它们。例如:在
lib/start_or_end_action.rb
中编写第二个解决方案的优点是
before_filter
和after_filter
仅在需要时定义。缺点是您必须将该模块包含到每个控制器中,您可以在其中配置要发生的前置过滤器。第一种方法的优点是可以覆盖任何控制器,并且检查前后过滤器会产生一些开销。
希望这有帮助。
I see two options to reach your goal.
First approach: declare both the filters inside the
ApplicationController
and inside the filter check whether thecontroller_name
andaction_name
match any in your yaml-configuration. If they match, execute it, if not ignore.In code that would like
I hope you get the idea.
Second approach: a clean way to define
before_filter
is to define them in a module. Normally you would use theself.included
method to define thebefore_filter
, but of course, you can define them conditionally. For example:and in
lib/start_or_end_action.rb
you writeThe advantage of the second solution is that the
before_filter
andafter_filter
are only defined when needed. The disadvantage is that you will have to include the module into each controller where you could possible configure the before-filter to take place.The first has the advantage that any controller is covered, and you get a little overhead checking the before- and after filter.
Hope this helps.