1

我在我的lib文件夾模塊中有一個API調用,它返回我需要在我的視圖中使用的變量。 例如:我定義我的模塊中從lib模塊傳遞實例變量到控制器

module ProdInfo 
    def get_item_info(id) 
    @url = "Blah" 
    end 
end 

我控制器以下:

class RecommendationsController < ApplicationController 
    require 'get_prod_info' 
    include ProdInfo 

    def index 
    @product = Product.find(params["product_id"]) 
    get_item_info(@product.id) 
    end 
end 

我想在我的建議,呼籲@url查看,但其沒有被正確調用。如果我將@url放入模塊中,它會打印出正確的URL,但如果我在控制器中執行相同操作,則不會輸出任何內容。

+0

我想你的問題,現在你可以返回的URL在你的方法一做你的控制器:'@ url = get_item_info(@ product.id)' – Kaeros 2013-02-25 18:59:45

+0

爲什麼要爲'ProdInfo'命名模塊需要'get_prod_info'?這些名字不匹配很奇怪。您是否記得在更換模塊後重新啓動服務器? – jdl 2013-02-25 19:13:39

+0

我的lib文件被稱爲get_prod_info.rb,它的標題應該與我的模塊相同嗎?是的,確保重新啓動我的服務器後,對我的模塊進行更改 – Yogzzz 2013-02-25 19:15:17

回答

0

這實質上是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. 
+0

我有我的'get_item_info'方法中定義的多個變量,我需要在我的視圖中使用。 – Yogzzz 2013-02-25 19:33:51

+0

所以只要將'get_item_info'打包成一個散列,然後你可以在視圖中訪問它。我會更新代碼。 – jstim 2013-02-25 19:36:05

相關問題