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

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

    I am adding another answer now that we have updated to 3.2.X. Leaving the old answer as it was in case someone needs that one. But, I will edit it to direct people to this one for current versions.

    The significant difference here is to make use of the "new" (since 3.1) availability of adding in custom path resolvers. Which does make the code shorter, as Jeroen suggested. But taken a little bit further. In particular the #find_templates is no longer private and it is expected that you will write a custom one.

    # lib/fallback_resolver.rb
    class FallbackResolver < ::ActionView::FileSystemResolver
      def initialize(path, fallbacks = nil)
        @fallback_list = fallbacks
        super(path)
      end
    
      def find_templates(name, prefix, partial, details)
        format = details[:formats].first
    
        return super unless @fallback_list && @fallback_list[format]
    
        formats = Array.wrap(@fallback_list[format])
        details_copy = details.dup
        details_copy[:formats] = formats
        path = Path.build(name, prefix, partial)
        query(path, details_copy, formats)
      end
    end
    
    # app/controllers/application_controller.rb
    class ApplicationController < ActionController::Base
      append_view_path 'app/views', {
        mobile: [:sponsor_mobile, :mobile, :sponsor_html, :html],
        html: [:sponsor_html, :html]
      }
      respond_to :html, :mobile
    
    # config/initializers/mime_types.rb
    register_alias 'text/html', :mobile
    

提交回复
热议问题