ruby-on-rails - 向 application_controller 添加一个方法,以便它对所有 Controller 和 View 可见

标签 ruby-on-rails ruby

我想创建一个在所有 Controller 和 View 中都可用的方法。

这个方法实际上调用了一个数据库来取回数据,所以因为它不会一直被使用,所以我希望它被延迟加载。

class ApplicationController < ActionController::Base


  def some_method
    @object = customdb.call_method(....)
  end

end

要使其延迟加载,我该怎么做?

@object ||= ....

我如何将其传播到所有 Controller 和 View 页面?

最佳答案

使用 helper_method ApplicationController 中使 some_method 在任何 Controller 或 View 中可用:

class ApplicationController < ActionController::Base
  helper_method :some_method

  def some_method
    @object ||= customdb.call_method(....)
  end
end

||= 按请求缓存,而不是延迟加载。延迟加载是 deferred initialization模式。

View 中的大范围和 Controller 方法是代码味道。最好最小化对象范围和 View 逻辑。

关于ruby-on-rails - 向 application_controller 添加一个方法,以便它对所有 Controller 和 View 可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6158065/

相关文章:

ruby-on-rails - Development.log 日志文件不记录 Rails SQL 查询

ruby-on-rails - 按联接表的列排序

ruby-on-rails - 显示每个rspec示例的运行时

ruby-on-rails - "Unable to autoload constant User"开发中更改代码时出错

ruby - 手动安装了 Ruby 1.9.3,但 ruby​​ -v 显示没有这样的文件或目录

ruby-on-rails - 无法将瘦服务器作为服务启动,RubyGems : Could not find thin

ruby - 如何访问 Ruby 中 case 语句的参数?

Ruby:JSON.parse 返回未定义的方法 `bytesize'

ruby - 在 Gemspec 中定义 gem 版本

javascript - 更新应用程序布局图标