Extend ActionController::Base within an application

689 views Asked by At

I'd like to expose a method to my controllers and views in the same fashion that plugins like Devise and Sorcery expose a current_user method. In fact I am piggybacking on this very functionality. However my attempts to divine the proper syntax for this wizardry haven't panned out. Here's what I've got so far...

# config/initializers/extra_stuff.rb
module ExtraStuff
  class Engine < Rails::Engine
    initializer "extend Controller with extra stuff" do |app|
      ActionController::Base.send(:include, ExtraStuff::Controller)
      ActionController::Base.helper_method :current_username
    end
  end
end

module ExtraStuff
  module Controller
    def self.included(klass)
      klass.class_eval do
        include InstanceMethods
      end
    end

    module InstanceMethods
      def current_username
        current_user.username
      end
    end
  end
end

When I attempt to call current_username from a controller action or a view, I get the usual undefined error:

undefined local variable or method `current_username'

The purpose of this method is app-specific, I don't need to make a plugin. I only mention this because the reference material I've dug up thus far only discusses this issue from the perspective of building Rails engines/plugins. Of course at this point that's exactly what my code does, and it still doesn't work. o.O

Running Rails 4.2

Update: I was able to get the functionality working by moving the stuff inside Rails::Engine up and out.

module ExtraStuff
  module Controller
    def current_username
      current_user.username
    end
  end
end

ActionController::Base.send(:include, ExtraStuff::Controller)
ActionController::Base.helper_method :current_username

However I don't understand why that was even necessary. The Rails Engine should have initialized with those extensions to ActionController::Base. What am I missing?

0

There are 0 answers