ruby-on-rails - 如何使方法出现在所有 Controller 操作之前

标签 ruby-on-rails controller helper

我的 Rails 应用程序中有几个 Controller (UserController、PostController、SessionController 等...)

在所有每个操作之前,我想使用 gon gem. 传递一个 json 对象

我已将这行代码添加到我的应用程序帮助程序中:

module ApplicationHelper

   ...

  def adding_gon
      gon.signed_in = signed_in?      
  end
end

我还添加了可供所有 Controller 使用的 ApplicationHelper:

class ApplicationController < ActionController::Base
  include ApplicationHelper
end

问题是现在我需要转到每个 Controller 并编写这行代码:

before_filter :adding_gon

将这行代码写入每个 Controller 相当重复。

有没有办法让这个方法在所有操作之前执行?

最佳答案

由于 Controller 通常继承自 ApplicationController,因此您不必将 before_filter 添加到每个 Controller 。只需在 ApplicationController 的类定义中添加这一行,过滤器就会在所有子 Controller 操作之前执行,除非您是从其他 Controller 继承的。

关于ruby-on-rails - 如何使方法出现在所有 Controller 操作之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12167777/

相关文章:

ruby-on-rails - 欺骗 Rails 应用程序使其认为它在不同的端口上

java - 从 angularJs 调用 java Controller

java - 将带有句点的 Json 属性映射到 Spring Controller 中的类属性

asp.net-mvc - MVC单元测试 Controller 的优势

android - 如何在android中打开 Crystal 报表

ruby-on-rails - 无法在 Debian 上安装 Capybara-Webkit

ruby-on-rails - 如何从 Rails gem 或 lib 中访问 session 和 cookie?

ruby-on-rails - 编写方法时遇到问题

c - 相同的二进制搜索在一种情况下不起作用,但在另一种情况下工作

asp.net - Url.Action 如何在 Asp.net MVC 中工作?