我想创建一个在所有 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/