online coding interviews

[why?] [how?]
the way we do the things we do

Managing your Admin namespace in Rails 3.1

Most web applications require some level of administrative functionality. Clearly, requires for your admin interface depend on the application, but there are often some common themes/requirements tend to arise:

  1. Typically you serve all of your adminstrative pages under a /admin namespace. E.g. In addition to feeling “clean” this allows fancy Apache configs to restrict access to within your office IP, etc.
  2. Admin pages tend to have a more utilitarian look and feel then the rest of your site. Maybe you want to re-use your main site header and footer, but within the main content area, you often want to lower the font size and remove any distracting bells and whistles.

Here’s a little recipe that spells out one method of achieving this in a Rails 3.1 environment.

Let’s suppose we’re running a book review website. Only administrative users can write reviews. Authenticated non-administrative users are allowed to read reviews, and vote them up/down. Here’s how we would structure such a site:


Let’s peek inside a few pieces an see how it’s wired together.

# routes.rb
Example::Application.routes.draw do
    resources :users
    resources :reviews, :only => [:index, :show]

    namespace :admin do
        resources :users
        resources :reviews

This routes.rb file will, for example, serve the administrative ability to create a new review at /admin/reviews/new and the public ability view a review at /reviews/1.

That’s all pretty simple. Now, what about the CSS and JS?

Serving Javascript For Your Admin Namespace

Our goal here is to serve some admin-specific javascript to only those views under the admin namespace.

First, remove require_tree from application.js and replace with

//= require jquery_ujs
//= require users
//= require reviews

Next, place your admin specific javascript in the admin.js file and the following method to ApplicationHelper.

def admin?"::").first=="Admin"

Finally, in application.html.erb add the following line inside the head element:

<%= javascript_include_tag "admin" if admin? %>

Serving CSS For Your Admin Namespace

The goal here is to define a set of CSS rules that are applied only to our views served under the admin namespace.

First, in application.html.erb add the following snippet to the body tag.

<body class="<%= 'admin' if admin? %> 

Then, put all your admin-specific CSS in the admin.css.scss file, which should have the following

body.admin {

    // Put all your admin CSS in here

And there you go, with a small amount of set-up we’ve achieved a maintenance-free separation of admin and public controllers, views, Javascript and CSS.

Blog comments powered by Disqus