2012-11-05 55 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文件夹中的所有文件。