首页 文章

了解Rails中的lib目录

提问于
浏览
0

我是Rails的新手,我正在尝试学习Rails中的 /lib/ 目录如何工作 - 以及如何引用 /lib/ 目录中定义的变量以供在视图中使用 .

我有一个名为 helloworld.rb 的文件,它保存在Rails的/ 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 %>

我错过了什么?

3 回答

  • 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实例变量 .

  • 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文件夹中的所有文件 .

  • 0

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

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

相关问题