Jeremy Smith on May 04, 2015

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

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


  def namespace[0,'::') || 0].downcase

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

class ApplicationController < ActionController::Base
  helper_method :namespace


  def namespace
    @_namespace ||=

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 %>

Need help building or maintaining a Rails app?

Jeremy has availability for new projects starting Q3 or Q4 of 2022.

Email Jeremy