Ruby on Rails Mobile Application

前端 未结 1 1365
夕颜
夕颜 2021-02-06 18:11

I am trying to develop a Ruby on Rails application that will detect the client i.e the mobile (browser) that connects to the server and render the appropriate layout. I tried

相关标签:
1条回答
  • 2021-02-06 18:38

    The most elegant solution for this I've seen is to do two things: recognize mobile users based on user-agent in the request and use a custom Rails mime type to respond with, allowing custom HTML templates for mobile users.

    Define a custom 'mobile' Rails MIME type in config/initializers/mime_types.rb that's just HTML:

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

    Add a helper/filter to respond to mobile users:

    def mobile_user_agent?
      @mobile_user_agent ||= ( request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(Mobile\/.+Safari)/] )
    end
    

    then..

    before_filter :handle_mobile
    
    def handle_mobile
      request.format = :mobile if mobile_user_agent?
    end
    

    Make custom mobile template:

    app/views/users/show.html.erb => app/views/users/show.mobile.erb
    

    Dispatch mobile or regular in controllers:

    respond_to do |format|
      format.html { }   # Regular stuff
      format.mobile { } # other stuff
    end
    
    0 讨论(0)
提交回复
热议问题