Understanding the Rails /lib/ Directory

I am trying to learn how the Rails /lib/ directory works - and how to
reference variables defined in a file placed in the the /lib/
directory for use in a View.

I have a file called helloworld.rb and it’s saved in the /lib/
directory in my Rails application.

The helloworld.rb file has the following code:

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

I want to be able to display the results of this method on a View
called index.html.erb, so I include the following code in the
index_helper.rb file:

module IndexHelper
  require 'HelloWorld'

Also, I include the following code on the view index.html.erb:

<%= @howdy %>

I’ve read where I need to include the following line in the /config/
application.rb file:

config.autoload_paths += %W(#{config.root}/lib

However, my preference is to load this module only when the View
renders the page, not when the Application loads. What am I missing?

Thank you

On Tuesday, November 6, 2012 8:49:16 PM UTC, scottc wrote:

renders the page, not when the Application loads. What am I missing?

You’re not so much missing what the lib folder does as misunderstanding
what modules do. As an aside, loading stuff on demand isn’t thread safe
usually best avoided in production.
Just requiring a file doesn’t do anything other than load that file. If
wanted to include a module then you’d need to do

module IndexHelper
include HelloWorld

in fact in your controller you could

helper HelloWorld

instead. Even this won’t cause @howdy to be set - that would only be set
when that hello method is called.