What's the easiest way to detect the user's operating system in Rails 3?

前端 未结 4 1305
难免孤独
难免孤独 2021-02-07 20:01

Simple Rails app, mostly scaffolding. I want to detect whether the user is using Android or iPhone to access my app. What\'s the easiest way to do that?

4条回答
  •  情书的邮戳
    2021-02-07 20:59

    I know this question is old, but in case this helps someone else, I use this method in application_controller.rb to automatically set the format to :mobile:

    before_filter :detect_mobile
    
    protected
    
    def detect_mobile
      request.format = :mobile if mobile?
    end
    
    def mobile?
      request.user_agent =~ /iPhone|iPad|Android/i
    end
    

    The mobile? method is separate so that you can also use it in your own controllers if you need to do some sort of conditional logic for mobile browsers.

提交回复
热议问题