A simple interface for the controller context in your Rails app

Oftentimes in a Rails app, you namespace your controllers based on the context. Admin:: will namespace all your admin controllers, Members:: may namespace all the controllers in your members-only area.

Have you ever needed to know the namespace context in your layout? Here’s a simple interface you can use:

First, drop the following Namespace class into your lib folder. It’s going to determine the first namespace from your controller class. If there’s no namespace, then it will return global.

class Namespace
  attr_reader :controller

  def initialize(controller)
    @controller = controller
  end

  def name
    namespace.blank? ? "global" : namespace
  end

  private

  def namespace
    @controller.name[0, @controller.name.index('::') || 0].downcase
  end
end

Now, you’ll need to create a namespace helper method in your application controller:

class ApplicationController < ActionController::Base
  helper_method :namespace

  protected

  def namespace
    @_namespace ||= ActiveSupport::StringInquirer.new(Namespace.new(self.class).name)
  end
end

Note: StringInquirer is the same class used by Rails.env, allowing you to either get the string value of the current environment, or check the value of the current environment: Rails.env.production?

Now, in your view, you can get the current namespace. Maybe you want to render a different footer partial for each namespace context of your app. You could do this:

<%= render "layouts/footers/#{namespace}" %>

You can also check the value of the namespace. Maybe you have a javascript file that you only want to include on admin pages. You could do this:

<% if namespace.admin? %>
    <%= javascript_include_tag "admin" %>
<% end %>

Posted May 4, 2015 at 5:49 pm