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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With