Friday, July 11, 2008

Add Custom Conditions to your Rails Routes

At MeetingWave we support both a Social Network Application and the main Web Application. On occasion we need to know which context we are in in order to direct the request to the correct controller/action pair. What we want is to be able to have a route that looks like this:

map.facebook_my_profile 'myprofile', :controller => 'member_profiles', :action => 'import_facebook_profile', :conditions => {:context => "social_network" }



Currently, at least as of Rails 2.0 , the only condition that you can use is the request type ( e.g. :conditions => {:method => "get"}) . Maybe things are different in 2.1, we haven't made the plunge yet.

Anyway here is some code, that I coerced from the Facebooker source, that will enable the route above to work:

module TTB
module RouteSetExtensions
def self.included(base)
base.alias_method_chain :extract_request_environment, :context
end

def extract_request_environment_with_context(request)
env = extract_request_environment_without_context(request)
env.merge :context => request.parameters[:context]
end
end
end

class ActionController::Routing::Route
def recognition_conditions_with_context
defaults = recognition_conditions_without_context
defaults << " env[:context] == conditions[:context] " if conditions[:context]
defaults
end
alias_method_chain :recognition_conditions, :context
end

ActionController::Routing::RouteSet.send :include, TTB::RouteSetExtensions




Someday I will get my Textmate code highlighting to work in here, sorry about that.

No comments: