This is an evolving issue related to a previous posting I made…
I am playing around some – to try to learn how the /lib/ directory in Rails works – and how to reference variables defined in the /lib/ directory for use in a view.
I have a file called helloworld.rb and it’s saved in a /lib/hellotest/ directory in Rails.
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.erb file:
module IndexHelper
require 'helloworld'
end
I have learned that I need to include the following line of code in the /config/application.rb file:
config.autoload_paths += %W(#{Rails.root}/lib/hellotest/)
Also, I include the following code on the view index.html.erb:
<%= @howdy %>
I think I may have found something that is causing problems. I didn’t want to load the entire /lib/ directory at startup so I put the file in a subdirectory called /lib/hellotest/. I’ve read there are some issues with how Rails interprets module/class naming conventions in the lib folder, but I can’t quite figure it out. I see a good resource regarding this possible solution to my problem on William B Harding’s Blog, on point 2 – but I can’t quite get my arms around this solution as it pertains to my problem.
Any advice please?
What am I missing?
I’d suggest that unless you have a good reason to do otherwise, follow the conventional naming for modules and classes (as described in the link you provided). Rename
helloworld.rbtohello_world.rb, move it intolib, and change yourautoload_pathsto:Finally, change
require 'hello_world'torequire 'hello_world'in yourIndexHelpermodule. It should then load normally.