这本质上是 Kaeros 的评论在两个地方都扩展到了代码中。
您只需要将变量保存在控制器中而不是 lib 文件夹中。你在 lib 中的文件不应该知道你的模型的需求,它会很高兴返回一个值而不知道在哪里或如何保存它。
module ProdInfo
def get_item_info(id)
# in your comment you said you have multiple values you need to access from here
# you just need to have it return a hash so you can access each part in your view
# gather info
{ :inventory => 3, :color => "blue", :category => "tool"} # this is returned to the controller
end
end
Rails 3 还有一个配置变量,允许您指定要加载的路径,我相信默认值包括 lib 路径。这意味着您不需要所有require
条目。你可以打电话给这Module#method
对。
class RecommendationsController < ApplicationController
# require 'get_prod_info'
# include ProdInfo
# => In Rails 3, the lib folder is auto-loaded, right?
def index
@product = Product.find(params["product_id"])
@item_info = ProdInfo.get_item_info(@product.id) # the hash you created is saved here
end
end
以下是在视图中使用它的方法:
# show_item.text.erb
This is my fancy <%= @item_info[:color] %> item, which is a <%= @item_info[:type] %>.
I have <%= @item_info[:inventory] %> of them.