Skip to content

Per Request Configuration

scambra edited this page Sep 15, 2010 · 5 revisions

This is an advanced and experimental technique. It may have unknown quirks.

Sometimes you need to configure your scaffold differently for each request. At some level you can do this with the security layer, e.g. authorizing/forbidding the update action. But if you need to fiddle with things not covered by the security layer, you can use a before_filter to modify the configuration per-request. The basic setup is like this:

before_filter :update_table_config

def update_table_config         
  if current_user
    # Change things one way
  else
    # Change things back the other way
  end 
end

Probably the most obvious change is to add or remove columns from the table or to change the column’s (or table’s) labels (giving for example Scott’s Tags or Richard’s Tags instead of just Tags). In order to add or remove columns the way to go is to define all the required columns in the initial configuration and then exclude those that are unwanted in the before_filter. Labels can be updated by a simple assignment.

Don’t forget to change the configuration back to the way it was! In the production environment the configuration is cached, and changing it for one special user will change it for all users … unless you change it back.

def update_table_config
  if current_user 
    active_scaffold_config.list.columns.exclude :not_required
    active_scaffold_config.label = current_user.name
    active_scaffold_config.columns[:tags].label = current_user.name+"'s Tags"
  else
    active_scaffold_config.list.columns.add :not_required
    active_scaffold_config.label = 'Users'
    active_scaffold_config.columns[:tags].label = 'Tags'
  end
end
Clone this wiki locally