Context-Based Rails 3 Routing

I am trying to implement a “contextual” system similar to the one used by GitHub. For example, a Post can be created either belonging to the User, or one of the companies to which the User belongs, depending on whether the user is in the "User" context or in the context related to one of the companies.

As part of this, I would like to be able to perform routing based on the current context of the user. For example, if the user is in his own context, he /dashboardshould go to users/show, but if they are in the context for the Company with ID 35, he /dashboardshould go to companies/35/dashboard.

I could direct /dashboardto a special controller responsible for making such decisions, for example context#dashboard, which I could do redirect_to, but this is not entirely correct (perhaps because we take the logic that the Rails routing module should respond to and move it to the controller?)

What would be the right way to solve this problem in Rails 3?

+5
source share
2 answers

I finally found a solution to my problem that I like. This will use the urls from my original question.

Context, , , . "", , , . get_context, current_user.

:

config/routes.rb:

MyApplication::Application.routes.draw do
  get "dashboard" => "redirect", :user => "/users/show", :company => "/companies/:id/dashboard"
end

app/controllers/redirect_controller.rb:

class RedirectController < ApplicationController
  def method_missing(method, *args)
    user_url    = params[:user]
    company_url = params[:company]
    context     = get_context

    case context.type
    when :user
      redirect_to user_url.gsub(":id", current_user.id.to_s)
    when :company
      redirect_to company_url.gsub(":id", context.id.to_s)
    end
  end
end

URL- , ( routes.rb!), DRY. .

+2

. .

0

All Articles