controller snippets

How to create configurable Rails controllers

Tagged controller, write_inheritable_attribute, read_inheritable_attribute, configurable  Languages ruby

Beware this is a rough example of how to create configurable Rails controllers that hasn't been tested...

Somewhere in application.rb, preferrably at the top:

class ActionController::Base
  def self.stylesheets(*params)
    if params.any?
      # do something here...
      write_inheritable_attribute(:stylesheets, params)
    else
      read_inheritable_attribute(:stylesheets)
    end
  end

  helper_method :stylesheets
  def stylesheets
    self.class.read_inheritable_attribute(:stylesheets)
  end
end

Then in your controllers:

class ApplicationController < ActionController::Base
  stylesheets '...'
end

class MegaShit < ApplicationController
  stylesheets '...'
end

In your views, via the helper_method (optional):

<%= stylesheets %>

Rails Cells Example

Tagged rails, cells, request, session, params, controller  Languages ruby

This Rails Cells example demonstrates how to: * access the request * access the controller * access the session * access the request parameters * cache data * use dynamic cache keys * access cell parameters * use helpers

class MenuCell < Cell::Rails
  helper :menu
  cache :display, :cache_conf, :expires_in => 1.day

  def display
    @selected = options[:selected]
    @posts ||= Post.paginate(options[:posts])
    render
  end

  protected
    def cache_conf
      # parent_controller.controller_name
      # parent_controller.request or request
      # parent_controller.session
      # parent_controller.params
      { :path => request.fullpath }
    end
end

The cell is rendered by calling:

<%= render_cell :menu, :display, :selected => controller.controller_name %>

See Cells the change log for details.