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

后端 未结 15 1291
余生分开走
余生分开走 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 22:37

    Here is another example of how to do it, inspired by Simon's code, but a bit shorter and a bit less hacky:

    # application_controller.rb
    class ApplicationController < ActionController::Base
      # ...
    
      # When the format is iphone have it also fallback on :html
      append_view_path ExtensionFallbackResolver.new("app/views", :iphone => :html)
    
      # ...
    end
    

    and somewhere in an autoload_path or explicitly required:

    # extension_fallback_resolver.rb
    class ExtensionFallbackResolver < ActionView::FileSystemResolver
    
      attr_reader :format_fallbacks
    
      # In controller do append_view_path ExtensionFallbackResolver.new("app/views", :iphone => :html)
      def initialize(path, format_fallbacks = {})
        super(path)
        @format_fallbacks = format_fallbacks
      end
    
      private
    
        def find_templates(name, prefix, partial, details)
          fallback_details = details.dup
          fallback_details[:formats] = Array(format_fallbacks[details[:formats].first])
    
          path = build_path(name, prefix, partial, details)
          query(path, EXTENSION_ORDER.map { |ext| fallback_details[ext] }, details[:formats])
        end
    
    end
    

    The above is still a hack because it is using a private API, but possibly less fragile as Simon's original proposal.

    Note that you need to take care of the layout seperately. You will need to implement a method that chooses the layout based on the user agent or something similar. The will only take care of the fallback for the normal templates.

提交回复
热议问题