escort-mission

Escort missions. They’re like Take Your Child to Work Day, only your job involves getting shot at and your child is a mental deficient with a lousy sense of direction and giant target painted on his back.

Unfortunately, no matter how much story is piled on top of these scenarios, the missions rarely feel like more than a chore, leaving you feeling less like the savior of the universe and more like a hired thug with little else to do but watch other people do more interesting, less violent work; the Blackwater mercenary of the videogame land, escorting pencil pushers to the Green Zone.

www.escapistmagazine.com/articles/view/issues/issue_124/2644-Escort-Missions-Suck

Escort Mission provides a well-mannered escort for your models. Typically, this is how you might scope and filter models in a standard rails app:

def index
  if admin?
    @posts = Post.all
    json   = @posts.to_json
  else
    @posts = Post.published
    json   = @posts.to_json(:except => [:secret_token, :editor_id])
  end
  render :json => json, :callback => params[:callback]
end

You can replace some of the logic in an Escort class:

def index
  @escort = Post::Escort.new(self)

  #scope automatically adds published scope if user is not an admin
  @posts = @escort.scope.all

  #filter adds the :except hash if the user is not an admin
  render :json => @posts.to_json(@escort.filter), :callback => params[:callback]
end

You can use the #api method to wrap up the rendering for you.

def index
  @escort = Post::Escort.new(self)
  @posts  = @escort.api.all
end

Here’s an example of what the Post escort might look like:

class Post::Escort < EscortMission
  include EscortMission::ActiveRecord, EscortMission::ActionPack
  attr_reader :user

  def initialize(*args)
    super
    @user = @controller.send(:current_user)
  end

  def scope
    @scope ||= begin
      s = Post
      s = s.published if @user.admin?
      s
    end
  end

  def filter
    if @user.admin?
      {}
    else
      {:except => [:secret_token, :editor_id]}
    end
  end
end

Copyright © 2009 kabuki. See LICENSE for details.