Rails ActionController 为每个操作执行相同的代码

发布于 2024-08-21 01:22:02 字数 114 浏览 2 评论 0原文

对于那里的 Rails 专家,我想知道您将在哪里/如何为 Web 应用程序中的每个操作执行相同的代码?如果您能给我指出一篇文章或提供一个简短的代码片段,我将不胜感激。

预先感谢任何可以提供帮助的人。

To the rails experts out there I was wondering where/how you would execute the same code for every action in your web application? If you can point me to an article or provide a short code snippet I would greatly appreciate it.

Thanks in advance to anyone who can help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

病毒体 2024-08-28 01:22:02

在 ApplicationController 中使用过滤器来运行应用程序中每个操作的代码。所有控制器都源自 ApplicationController,因此将过滤器放在那里将确保过滤器运行。

class ApplicationController
  before_filter :verify_security_token
  def verify_security_token; puts "Run"; end;
end

Use a filter in your ApplicationController to run the code for every action in your application. All your controllers descend from ApplicationController, so putting the filter there will ensure the filter gets run.

class ApplicationController
  before_filter :verify_security_token
  def verify_security_token; puts "Run"; end;
end
捶死心动 2024-08-28 01:22:02

在我看来,您好像在谈论过滤器

class MyController < ActionController::Base
  before_filter :execute_this_for_every_action

  def index
    @foo = @bar
  end

  def new
    @foo = @bar.to_s
  end

  def execute_this_for_every_action
    @bar = :baz
  end
end

如果您希望每个控制器都运行过滤器,您也可以将过滤器放在 ApplicationController 上。

It sounds to me like you're talking about filters.

class MyController < ActionController::Base
  before_filter :execute_this_for_every_action

  def index
    @foo = @bar
  end

  def new
    @foo = @bar.to_s
  end

  def execute_this_for_every_action
    @bar = :baz
  end
end

You can put the filter on the ApplicationController, too, if you want every controller to run it.

仄言 2024-08-28 01:22:02
  • before_filter 如果您希望代码在每个操作“之前”执行。

  • 每次使用该操作时都声明该操作,可以将其放入 ApplicationController 中并在任何控制器中调用该方法。

另一种方法是使用类似的帮助器:

module PersonHelper
   def eat
     {.. some code ..}
   end
end

在你的控制器中:

class MyController < ActionController::Base
  include PersonHelper

  def index
     eat
  end
end
  • before_filter if you want the code to be executed "before" each action.

  • If you want the action to be declared each time you use it, you can put it in ApplicationController and call the method in any controller.

Another approach is to use helpers like:

module PersonHelper
   def eat
     {.. some code ..}
   end
end

And in your controller:

class MyController < ActionController::Base
  include PersonHelper

  def index
     eat
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文