Rails, Sprockets, and Resource Controller
I had an annoying bug recently while using Sprockets on a couple of Rails projects. Every time I restarted my app server, I’d end up with an exception on the first page load:
ActionView::TemplateError (undefined local variable or method `sprockets_include_tag' for #<ActionView::Base:0x1035fa6a0>)...
But everything was fine after that first request until I restarted the server again, obviously making it a pain in the ass to debug. Eventually, I ended up creating a fresh Rails project with all my gem requirements and removing gems until the error disappeared.
It turned out to be Resource Controller, or more specifically, the way I was invoking Resource Controller. I chose to inherit from ResourceController::Base
rather than simply calling resource_controller
in my controllers, which meant that I was no longer inheriting from ActionController::Base
, and that’s where Sprockets injects itself:
# vendor/sprockets-rails/init.rb
class ActionController::Base
helper :sprockets
end
My solution was to create an initializer to include the Sprockets helper in ApplicationController
, since ResourceController::Base
subclasses it:
# config/initializers/sprockets.rb
ApplicationController.class_eval do
helper :sprockets
end
And that was that!