Access current request within routes.rb?

Go To


I have this in my routes.rb file:

class SubdomainWww
  def self.matches?(request)  
    request.subdomain.start_with? "www."

  def self.strip_www(subdomain)
    if subdomain.start_with? "www."

MyApp::Application.routes.draw do

  constraints(SubdomainWww) do
    match '*path', :to => redirect(:subdomain => SubdomainWww.strip_www(???))  
    match '/', :to => redirect(:subdomain => SubdomainWww.strip_www(???))  

The purpose if this is to remove the www. for subdomains (e.g. www.sub.domain.tld should be redirected to sub.domain.tld; the subdomain is later used to identify the client). How can I replace the '???' so that the subdomain(string) of the current request is passed to the function strip_www()?

Thanks in advance!

2012-04-04 21:17
by Daniel
I believe that this is a thing better solved on a more basic level. You can set a flag in the DNS settings, disallowing the www subdomain - Ekampp 2012-04-04 22:11
Yes, that might be right. But it should still be possible to solve it in that way. The method matches? can also access the requested subdomain... - Daniel 2012-04-05 13:12
It might be possible to make that work. I'm not sure how, and I'm not sure that it's the best way to go about the problem. So I will leave proposed solutions up to someone else. Good luck - Ekampp 2012-04-08 13:14


Don't know if this will work or help, but I had the same problem using Cells with Devise, where the Devise current_* methods would want env and warden which are stored in the request. I had a route to a Cell (Controller and View) which rendered the Cell's View for me. The way I got the request into the Cell's Controller was to pass self in as request from route.rb.

match "/dashboard/widget/:name" => proc { |env|
  cell_name = env["action_dispatch.request.path_parameters"][:name]
  [ 200, {}, [ Cell::Base.render_cell_for(cell_name, :display, :request => self) ]]

Note the :request => self. When you're in routes, self is the ActionDispatch::Request object itself. Just pass request along and you should be good.

MyApp::Application.routes.draw do

  constraints(SubdomainWww) do
    match '*path', :to => redirect(:subdomain => SubdomainWww.strip_www(self))  
    match '/', :to => redirect(:subdomain => SubdomainWww.strip_www(self))  
2012-04-19 00:10
by garlicman