Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility Classes In Ruby on Rails

This is probably a stupid question, but I'm new to Ruby on Rails and I could use a little guidance. I want to have a helper/utility class that performs a group of network operations and returns results. Where do I put that class and how do I use it.

I've created network_helper.rb in my app/modulename/helpers directory. In my controller when I try to do

  myNetworkHelper = ModuleName::NetworkHelper.new
  results = myNetworkHelper.getResults

I get an error

 undefined method `new' for MyModule::NetworkHelper:Module

I'm sure this is just a misunderstanding of how ruby on rails works. Can I get some clarification?

Would it be better to make this a class instead of a module and put it in libs? And can I add subfolders in libs and have them automatically loaded?

like image 386
codeetcetera Avatar asked Mar 10 '13 03:03

codeetcetera


3 Answers

Lib or Classes

Little utility classes like this typically go in the lib folder, though some people prefer to create a folder called classes. Whichever you choose, make sure you import the folder in config/application.rb, as the lib folder is not autoloaded:

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

Concerns

If instead of a utility class, you want to extend some of your models with reusable code, you may also wish to look at the new Rails 4 concerns folders which encourage you to extract reusable modules:

see: How to use concerns in Rails 4

like image 176
superluminary Avatar answered Oct 31 '22 18:10

superluminary


To use new, the thing your calling it on must be a class, not a module. You're using a module. Change module to class in lib/utilities/network_utility.rb.

like image 4
Linuxios Avatar answered Oct 31 '22 19:10

Linuxios


I cannot verify this at the moment, however I believe one place you can store your custom modules and classes is the lib directory. Alternatively, you should be able to store them in the app directory in the manner you have indicated by adding the following line to your environment.rb:

config.load_paths << File.join(Rails.root, "app", "modulename")

Also, check out Yehuda Katz's answer, which I think not only answers your question better, but also contains some very interesting and useful information and concepts relating to your situation. Hope that helps!

like image 1
Paul Richter Avatar answered Oct 31 '22 17:10

Paul Richter