Forum: Ruby on Rails Understanding the Rails /lib/ Directory

Posted by scottc (Guest)
on 2012-11-07 14:41
(Received via mailing list)
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!"
      end
    end

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'
    end

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
Posted by Frederick Cheung (Guest)
on 2012-11-07 14:50
(Received via mailing list)
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 
so
usually best avoided in production.
Just requiring a file doesn't do anything other than load that file. If 
you
wanted to include a module then you'd need to do

module IndexHelper
  include HelloWorld
end

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.

Fred
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.