Ruby on rails 学习Rails中的lib目录

Ruby on rails 学习Rails中的lib目录,ruby-on-rails,Ruby On Rails,我对Rails非常陌生,正在尝试学习Rails中的/lib/目录如何工作,以及如何引用/lib/目录中定义的变量以在视图中使用 我有一个名为helloworld.rb的文件,它保存在Rails的/lib/目录中 helloworld.rb文件包含以下代码: module HelloWorld def hello @howdy = "Hello World!" end end 我希望能够在名为index.html.erb的视图上显示此方法的结果,因此我在index\u helpe

我对Rails非常陌生,正在尝试学习Rails中的
/lib/
目录如何工作,以及如何引用
/lib/
目录中定义的变量以在视图中使用

我有一个名为
helloworld.rb
的文件,它保存在Rails的/lib/目录中

helloworld.rb
文件包含以下代码:

module HelloWorld
  def hello
    @howdy = "Hello World!"
  end
end
我希望能够在名为
index.html.erb
的视图上显示此方法的结果,因此我在
index\u helper.rb
文件中包含以下代码:

module IndexHelper
  require 'helloworld'
end
此外,我还在视图
index.html.erb
中包含以下代码:

<%= @howdy %>


我缺少什么?

您必须将lib文件夹添加到config/application.rb中的自动加载路径中

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

您应该将这些行中的任何一行添加到
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\u路径
也会加载lib文件夹中的所有文件。

您需要调用Helloworld::hello,以便它创建实例变量

也许你可以把它放在控制器的前置过滤器里

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
需要“helloworld”
类FooController<应用程序::控制器
在\u filter:setup\u hello之前,[:only=>:create,:edit]
def创建
#随便
结束
定义编辑
#随便
结束
你好
你好
结束
结束

因此,现在,每次编辑或创建操作时,都会执行“setup\u hello”,它调用模块中的hello方法,并设置@hello实例变量。

我肯定遗漏了什么。。。当我在我的控制器中实现这一点时,我得到了以下错误:Helloworld:ModuleHMM的未定义方法“hello”。。。我一定还是做错了什么,因为我收到了相同的错误消息。错误消息指向控制器中引用
Helloworld::hello
的行。另外,我是否正确地假设在视图中,我可以使用以下方法引用此代码:
?修复了另一个打字错误('HelloWorld')vs('HelloWorld')并为HelloWorld:Module Rails.root:C:/Rails\u projects/HelloWorld app/controllers/reports\u controller.rb:8:in'setup\u hello'。再加上你的帮助和我在这个主题上的其他帖子(),我终于找到了答案!我发现,只要我需要控制器中的文件,就不需要自动加载步骤。