Jim Pedid
Jim Pedid

Reputation: 2780

Ruby Rails Lib Folder Naming Convention

I seem to be having trouble with the naming conventions of the Lib Folder in Rails, and the error messages provided to me do not help. [For example, I have received a message saying that XXX::YYY::TextBox is expected to be defined xxx/yyy/text_box.rb, even though it clearly was defined there.] I think I'm getting the convention wrong.

Let's say I am working on YourModule::MyModule::MyClass. I clearly get that this file should be located in

lib/your_module/my_module/my_class.rb

But what should the actual file here look like? Which one of these (if either) are correct?

#your_module/my_module/my_class.rb
module YourModule
  module MyModule
    class MyClass
       ...
    end
  end
end

Or

#your_module/my_module/my_class.rb
class MyClass
  ...
end

In other words, do I need to nest the class inside of the module structure or not?

Upvotes: 6

Views: 4611

Answers (1)

Andrew
Andrew

Reputation: 43113

The lib folder has few conventions, as it is not autoloaded. So, how you organize the files is up to you, but you do have to name the classes correctly. Your first example is correct.

To get the files included you need to specify you want them in your application.rb file, see this example: Best way to load module/class from lib folder in Rails 3?

I would recommend making a folder just called lib/modules, since you probably won't have very many. Name the file my_class.rb. Then in application.rb you need:

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

That should take care of your issue.

Upvotes: 7

Related Questions