Skip to content

Instantly share code, notes, and snippets.

@ilpoldo
Created July 22, 2013 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilpoldo/6052044 to your computer and use it in GitHub Desktop.
Save ilpoldo/6052044 to your computer and use it in GitHub Desktop.
Rails3 mobile subdomain redirection example
module MobileDetect
class Constraint
def matches?(request)
return false if request.cookies[:full_site_form_mobile] || request.host.match(/^m./)
request.user_agent.to_s.match(/Mobile/)
end
end
# the following sucks and it makes sense to be more in control of what routes you want to expose for the mobile experience
class Middleware
def initialize(app)
@app = app
end
def call(env)
begin
request = Rack::Request.new(env)
if request.host.match(/^m./)
request.params[:format] = :mobile
request.env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(:mobile)]
end
return @app.call(env)
rescue => exception
Rails.logger.fatal(
"\n#{exception.class} (#{exception.message}):\n " +
exception.backtrace.join("\n") + "\n\n"
)
raise exception
end
end
end
end
Royale::Application.routes.draw do
constraints MobileDetect::Constraint.new do
root :to => redirect {|params, req| "http://m.#{req.domain}" }
match "*path" => redirect {|params, req| "http://m.#{req.domain}#{req.fullpath}" }
end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => 'welcome#index'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment