Just Read The Directions
(Because sometimes that helps.)
Articles on programming by Phil Darnowsky.

Announcing has_named_bootstraps (June 26, 2010)

Most nontrivial Web apps will require some amount of bootstrap data to be present in the database. Classic examples are lists of countries, US states, or postal codes. In my work at Children's Hospital Boston, we frequently deal with lists of clinics or diagnoses. If you're using role based access control (RBAC), you'll need different roles to be preloaded.

You might write part of the logic for RBAC like this:

class AdminController < ApplicationController before_filter :require_admin_user ... private def require_admin_user admin_role = Role.find_by_name 'admin' unless current_user.roles.include?(admin_role) flash.now[:error] = "You're not authorized to do that." redirect_to peon_path end end

But what's wrong with doing it this way?

Dan Chak, in his book Enterprise Rails, suggests that you create a constant to refer to this kind of data. I don't agree with everything in this book, but I do believe that this particular advice is on the money. So our example from above might turn into:

def require_admin_user unless current_user.roles.include?(Role::ADMIN) flash.now[:error] = "You're not authorized to do that." redirect_to peon_path end end

This could still be DRYer, but it's definitely a step in the right direction.

Having defined a few gazillion of these constants in some of my code, I wrote and recently open-sourced a gem called has_named_bootstraps (with source on GitHub) that automates defining these constants. There are plenty of options to play with, but the most basic case just looks like:

class Department < ActiveRecord::Base has_named_bootstraps( :R_AND_D => 'R&D', :MARKETING => 'Marketing', :HANDSOME_DEVILS => 'Web Development' ) end

The constants R_AND_D, MARKETING, and HANDSOME_DEVILS are now all defined on Department.

Feedback, bug reports and pull requests are all most welcome. I'm eager to hear what you think.

blog comments powered by Disqus