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


end

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…
/Users/josh/Sites/projects/psyguideorg/vendor/plugins/incense_authorization/lib/application_controller.rb:4:
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’
from
/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in
require' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/dependencies.rb:495:inrequire’
from
/usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/dependencies.rb:342:in
new_constants_in' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/dependencies.rb:495:inrequire’
from
/Users/josh/Sites/projects/psyguideorg/vendor/plugins/incense_authorization/lib/application_controller.rb:1
from
/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in
gem_original_require' from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:inrequire’
… 25 levels…
from
/usr/local/lib/ruby/gems/1.8/gems/rails-1.2.5/lib/commands/server.rb:39
from
/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in
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
Josh

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

class ActionController::Base
before_filter :prepare_user

end

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

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.

Fred

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: