谁能告诉我实现rail的before_filter方法的想法?(我想尝试编写自己的before_method)
特别是,我想知道 ruby 是否有一些方法来检测方法调用?
我的想法是:
步骤1:alias_method :old_method, :method
第2步:alias_method :method, :wrapper_method
step3:在 中wrapper_method,我们先做一些事情,然后调用old_method
有什么问题吗?
有人有更好的主意吗?
谁能告诉我实现rail的before_filter方法的想法?(我想尝试编写自己的before_method)
特别是,我想知道 ruby 是否有一些方法来检测方法调用?
我的想法是:
步骤1:alias_method :old_method, :method
第2步:alias_method :method, :wrapper_method
step3:在 中wrapper_method,我们先做一些事情,然后调用old_method
有什么问题吗?
有人有更好的主意吗?
如果您只想在调用任何其他方法之前触发一个方法,您可以简单地执行此操作before_filter
class UsersController < ApplicationController
before_filter :check_something
...
...
...
end
这样,该check_something方法将在调用该类的任何方法之前被调用。
only您也可以通过设置或except选项来限制这一点。喜欢
before_filter :check_something, :only =. [:show, :edit]
在这种情况下,该check_something方法将只为show和调用edit。
可能是值得一看的before_filter和after_filter文章。