2012-11-05 56 views
0

lib目錄中,我很新的Rails的,和我努力學習/lib/目錄Rails中是如何工作的 - 以及如何引用在/lib/目錄視圖中使用定義的變量。學習關於Rails中

我有一個名爲helloworld.rb文件,它保存在導軌上的/ lib /目錄。

helloworld.rb文件有以下代碼:

module HelloWorld 
    def hello 
    @howdy = "Hello World!" 
    end 
end 

我希望能夠顯示這些方法的一種稱爲index.html.erb視圖的結果,所以包括在index_helper.rb文件以下代碼:

module IndexHelper 
    require 'helloworld' 
end 

另外,我包括在視圖index.html.erb以下代碼:

<%= @howdy %> 

我錯過了什麼?

回答

1

您需要調用Helloworld :: hello才能創建實例變量。

,也許你可以把它放在一個的before_filter在控制器

require 'helloworld' 

class FooController < Application::Controller 

    before_filter :setup_hello , [:only=>:create, :edit ] 
    def create 
    # whatever 
    end 
    def edit 
    #whatever 
    end 
    def setup_hello 
    HelloWorld::hello 
    end 
end 

所以現在,每次你要麼你編輯或創建行動「 setup_hello」被執行,它調用hello方法的模塊中,並設置@hello實例變量。

+0

我必須缺少一些東西......當我在我的控制器中實現這個時,我得到以下錯誤:Helloworld的undefined方法'hello':模塊 – 2scottish

+0

...固定後,抱歉! – RadBrad

+0

嗯......我仍然在做錯事,因爲我得到了同樣的錯誤信息。錯誤消息指向控制器中引用'Helloworld :: hello'的行。 另外,我是否正確地假設,在視圖中,我可以通過使用:'<%= setup_hello%>'來引用此代碼? – 2scottish

0

你要的lib文件夾添加到配置/ application.rb中

# Custom directories with classes and modules you want to be autoloadable. 
# config.autoload_paths += %W(#{config.root}/lib) 
+0

我發現這個自動加載步驟並不是必須的,只要我在我的控制器中需要該文件即可。 – 2scottish

1

的自動裝載路徑你應該這些行config/application.rb文件。

module [App name] 
    class Application < Rails::Application 
    # Dir.glob("./lib/*.rb").each { |file| require file } 
    # config.autoload_paths += %W(#{Rails.root}/lib) 
    end 
end 

取消註釋任何註釋行。他們都做同樣的工作。

Dir.glob找到所有的.rb文件的應用程序,並要求在Rails應用程序的每個文件。

另外config.autoload_paths也加載lib文件夾中的所有文件。