Can a mobile mime type fall back to “html” in Rails?

后端 未结 15 1292
余生分开走
余生分开走 2020-12-23 22:17

I\'m using this code (taken from here) in ApplicationController to detect iPhone, iPod Touch and iPad requests:

before_filter :detect_mobile_request, :detec         


        
15条回答
  •  北海茫月
    2020-12-23 22:30

    You need to do several things to wire this up, but the good news is that Rails 3 actually makes this a lot simpler than it used to be, and you can let the router do most of the hard work for you.

    First off, you need to make a special route that sets up the correct mime type for you:

    # In routes.rb:
    resources :things, :user_agent => /iPhone/, :format => :iphone
    resources :things
    

    Now you have things accessed by an iphone user agent being marked with the iphone mime type. Rails will explode at you for a missing mime type though, so head over to config/initializers/mime_types.rb and uncomment the iphone one:

    Mime::Type.register_alias "text/html", :iphone
    

    Now you're mime type is ready for use, but your controller probably doesn't yet know about your new mime type, and as such you'll see 406 responses. To solve this, just add a mime-type allowance at the top of the controller, using repsond_to:

    class ThingsController < ApplicationController
      respond_to :html, :xml, :iphone
    

    Now you can just use respond_to blocks or respond_with as normal.

    There currently is no API to easily perform the automatic fallback other than the monkeypatch or non-mime template approaches already discussed. You might be able to wire up an override more cleanly using a specialized responder class.

    Other recommended reading includes:

    https://github.com/plataformatec/responders

    http://www.railsdispatch.com/posts/rails-3-makes-life-better

提交回复
热议问题