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

后端 未结 15 1196
余生分开走
余生分开走 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.

    0 讨论(0)
  • 2020-12-23 22:45

    The way that I'm handling this is to simply skip_before_filter on those requests that I know I want to render the HTML views for. Obviously, that will work with partials.

    If your site has a lot of mobile and/or tablet views, you probably want to set your filter in ApplicationController and skip them in subclasses, but if only a few actions have mobile specific views, you should only call the before filter on those actions/controllers you want.

    0 讨论(0)
  • 2020-12-23 22:45

    You can in this case for the format to html. By example you want always use the html in user show method

    class UserController
    
      def show
        ..your_code..
        render :show, :format => :html
      end
    end
    

    In this case, if you request show on User controller you render all the time the html version.

    If you want render JSON too by example you can made some test about your type like :

    class UserController
    
      def show
        ..your_code..
        if [:mobile, :tablet, :html].include?(request.format)
          render :show, :format => :html
        else
          respond_with(@user)
        end
      end
    
    end
    
    0 讨论(0)
提交回复
热议问题