Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put custom classes to make them globally available to Rails app?

Tags:

I have a class that I'm trying to use in my controller in the index action.

To simplify it, it looks like this

class PagesController < ApplicationController   def index     @front_page = FrontPage.new   end end 

FrontPage is a class that I have defined. To include it, I have placed it in the /lib/ folder. I've attempted to require 'FrontPage', require 'FrontPage.rb', require 'front_page', and each of those with the path prepended, eg require_relative '../../lib/FrontPage.rb'

I keep getting one of the following messages: cannot load such file -- /Users/josh/src/ruby/rails/HNReader/lib/front_page or uninitialized constant PagesController::FrontPage

Where do I put this file/how do I include it into a controller so that I can instantiate an object?

This is Rails 3.1.3, Ruby 1.9.2, OS X Lion

like image 275
Joshua Clark Avatar asked Feb 18 '12 04:02

Joshua Clark


Video Answer


1 Answers

You should be able to use require 'front_page' if you are placing front_page.rb somewhere in your load path. I.e.: this should work:

require 'front_page' class PagesController < ApplicationController   def index     @front_page = FrontPage.new   end end 

To check your load path, try this:

$ rails console ree-1.8.7-2011.03 :001 > puts $: /Users/scottwb/src/my_app/lib /Users/scottwb/src/my_app/vendor /Users/scottwb/src/my_app/app/controllers /Users/scottwb/src/my_app/app/helpers /Users/scottwb/src/my_app/app/mailers /Users/scottwb/src/my_app/app/models /Users/scottwb/src/my_app/app/stylesheets # ...truncated... 

You can see in this example, the first line is the project's lib directory, which is where you said your front_page.rb lives.

Another thing you can do is add this in your config/application.rb:

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

That should make it so you don't even need the require; instead Rails will autoload it then (and everything else in your lib dir, so be careful).

like image 110
scottwb Avatar answered Jun 01 '23 19:06

scottwb