Plugin: can't call before_filter in ApplicationController

Hi all

I want to outsource an extension for ApplicationController, that I had
in application.rb so far, into a plugin.

I have created this plugin, and in init.rb I load

require File.dirname(FILE) + ‘/lib/application_controller’

In lib/application_controller.rb I have the following code:

class ApplicationController
before_filter :prepare_user


This worked without a prolem so far.
But when I try to start Webrick now, I get the following error:

josh$ script/server
=> Booting WEBrick…
undefined method before_filter' for ApplicationController:Class (NoMethodError) from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:ingem_original_require’
require' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/dependencies.rb:495:inrequire’
new_constants_in' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/dependencies.rb:495:inrequire’
gem_original_require' from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:inrequire’
… 25 levels…
gem_original_require' from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:inrequire’
from script/server:3

What’s wrong here? Is the ApplicationController class not loaded already
when loading the plugin?

Thanks for help

I could work around it by just extending the ActionController::Base

class ActionController::Base
before_filter :prepare_user


But I guess this is not the perfect solution since I don’t really want
to extend the ActionController::Base class but the ApplicationController

I expect the problem here is that your plugin init code is running
before application.rb is loaded, so you’re defining a completely new
class. Since this class doesn’t descend from ActionController::Base
before_filter doesn’t exist.

On top of this, I think you’d find that since ApplicationController is
defined, rails would then not go and look for the
ApplicationController your application defines. You might have better
luck if you first require application_controller (forcing it to be
loaded, and then fiddle around adding filters to it.


I have refactored the whole code structure following the guidelines in
“Rails Plugins - Extending Rails beyond the Core” by Addison-Wesley
Professional Series and it works now. Thanks. :slight_smile: