Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.2 - How to redirect to a namespace?

In a Rails 3.2 application I'm doing I want to create some views (and action handling) specific for mobile devices. So I have created a namespace called mobile.

  namespace :mobile do
    resources :sessions
    resources :areas
  end  

For example if the user goes to the login page with a mobile I want to use the controller and views I make for that namespace.

So now I have two different ways to login:

new_mobile_session GET    /mobile/sessions/new(.:format)      mobile/sessions#new

and

new_session GET    /sessions/new(.:format)             sessions#new

But when a requests comes how could I add the "mobile" namespace to the request if it comes from mobile?

I.e. changing /sessions/new into /mobile/sessions/new

I am using Rack::MobileDetect but I don't know how to use the redirect_to for that purpose.

config.middleware.use Rack::MobileDetect, :redirect_to => '/mobile'

Or should I use a different approach?

Thanks.

like image 459
Pod Avatar asked Nov 14 '22 04:11

Pod


1 Answers

You could use a constraint for that. A Rails routing constraint either is class which responds to matches? or a lambda.

When a constraint is applied to a route, the route will only be considered if the constraint evaluates to true.

Consider this class

class MobileContraint
  def matches? request
     request.user_agent =~ /Mobile|webOS/
  end
end

You can now use this class in the routes like this:

resources :sessions
resources :sessions, :controller=> 'mobile/sessions', :constraints => MobileConstraint.new
like image 81
Mark Meeus Avatar answered Dec 01 '22 00:12

Mark Meeus