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

后端 未结 15 1322
余生分开走
余生分开走 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:41

    Here's a simpler solution:

    class ApplicationController
        ...
        def formats=(values)
            values << :html if values == [:mobile]
            super(values)
        end
        ...
    end
    

    It turns out Rails (3.2.11) adds an :html fallback for requests with the :js format. Here's how it works:

    • ActionController::Rendering#process_action assigns the formats array from the request (see action_controller/metal/rendering.rb)
    • ActionView::LookupContext#formats= gets called with the result

    Here's ActionView::LookupContext#formats=,

    # Override formats= to expand ["*/*"] values and automatically
    # add :html as fallback to :js.
    def formats=(values)
      if values
        values.concat(default_formats) if values.delete "*/*"
        values << :html if values == [:js]
      end
      super(values)
    end
    

    This solution is gross but I don't know a better way to get Rails to interpret a request MIME type of "mobile" as formatters [:mobile, :html] - and Rails already does it this way.

提交回复
热议问题