简体   繁体   中英

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

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. Ie: 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).

The file was named FrontPage.rb . Changing the name to 'front_page.rb', but leaving the class name as 'FrontPage' resolved the issue.

We just need to load the file,

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

lib/front_page.rb

class FrontPage
end

We can also set the application.rb to autoload these files

# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)

Second option would be a preferable solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM