0

I wanted to refactor some code out of a controller into a module, so I put the file into lib.

# lib/updat_lock.rb
module UpdateLock
  # ...
end

# app/controllers/boilerplates_controller.rb
class BoilerplatesController < InheritedResources::Base
  include UpdateLock
  # ...
end

But sadly, the file doesn't seem to be loaded, as I get an uninitialized constant BoilerplatesController::UpdateLock exception. What's wrong here? I thought the lib folder is always loaded automatically?

Update

Although a solution was provided, the thing I have forgotten was adding a require 'update_lock' on top of my controller file.

Joshua Muheim
  • 12,617
  • 9
  • 76
  • 152
  • 1
    You could try `::UpdateLock`, but the solution really depends on whether or not the file is really `updat_lock` (i.e., misspelled) and which version of Rails. – Dave Newton Jun 08 '15 at 14:06
  • http://stackoverflow.com/questions/3356742/best-way-to-load-module-class-from-lib-folder-in-rails-3 check this – K.M. Jun 08 '15 at 14:06
  • it isn't loaded automatically, by default. – Max Williams Jun 08 '15 at 14:08

1 Answers1

2

add this line to application.rb

config.autoload_paths += Dir["#{config.root}/lib/**/"]
Vrushali Pawar
  • 3,753
  • 1
  • 13
  • 22
  • While this works, it is actually a better idea to use `eager_load_paths` instead of `autoload_paths`. See [this blog post](http://blog.arkency.com/2014/11/dont-forget-about-eager-load-when-extending-autoload/). In the development environment however, you won't notice a difference :) – mario Jun 08 '15 at 14:08
  • Oh, I thought this is done by default by Rails. But I guess I was just confused because `lib` is in the load path, I mixed this up a little. So I just have to put a `require 'update_lock'` on top of my controller, and everything is working fine. Thanks! – Joshua Muheim Jun 08 '15 at 15:21