Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Providing context for Rails’ controller action

By Peter Cooper / July 13, 2006

There are many scenarios where you might want the same controller action / method in your Rails application to perform multiple functions. For example, a wizard with multiple steps or a single form with multiple-stage AJAX calls. What you want to do is provide a 'context' to the specific request and have the controller handle that in some different way.

Until now, one way to do this would be to use a parameter on the URL (e.g.: http://yourapp/post/show/1?stage=something_here) and then simply branch the logic based on the parameter. Bruce Williams saw an opportunity to make things a little better, and has developed in_context. It still uses a parameter on the URL or in the request, but he made the branching mechanism somewhat cleaner.

The in_context page provides the best info, but here's a quick demonstration of the branching:

render :update do |page|
	# Stuff at this point happens regardless of context
	in_context do |context|
		context.nil? do
			# This happens if no context is passed
		end
   		context.workflow_one do
			# One workflow goes through here..
   		end
   		context.workflow_two do
     		# And another through here..
   		end
 	end
end

Comments

  1. Danno says:

    Sounds a lot like how Continuation based frameworks work, except you can even undo steps in those.

  2. Jerrett says:

    it kinda looks like it's just a glorified case statement on params[:context] ...

    only i think a case statement might actually be a bit cleaner here

  3. Bruce says:

    Essentially it *is* a case statement. The plus here is you don't need to know what the param being passed is (especially if you're using the helpers on the view side), and that is reads differently than data manipulation code in your actions (ie, case statements, ifs, etc)-- it's a bit of syntactic sugar.

    It's just an abstraction I find useful, considering the size of my application and how often I have to deal with different workflows. I would probably use a case statement if didn't have to look at it so often.

Other Posts to Enjoy

Twitter Mentions