Created
July 22, 2013 07:49
-
-
Save ilpoldo/6052044 to your computer and use it in GitHub Desktop.
Rails3 mobile subdomain redirection example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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