【问题标题】:Rails way to detect mobile device?Rails 检测移动设备的方法?
【发布时间】:2015-03-16 02:40:49
【问题描述】:

是否有“rails 方式”来检测用户是否在使用移动设备?我的意思是我可以在 erb 中使用的一种方法,如下所示:

<% if mobile? %>

【问题讨论】:

    标签: ruby-on-rails ruby mobile


    【解决方案1】:

    您可以通过定义如下函数来做到这一点:

    def mobile_device?
      if session[:mobile_param]
        session[:mobile_param] == "1"
      else
        request.user_agent =~ /Mobile|webOS/
      end
    end
    

    或者您可以使用 gems 来检测移动设备,例如

    【讨论】:

    • 看起来 active_device 处于非活动状态。
    • 您能否将答案更新为您的答案和下面的答案,因为浏览器 gem 更常用,如 ruby-toolbox.com/projects/browser 所示
    • 如何测试它,我的意思是我如何告诉尊重我想现在作为移动设备运行它?
    • 代理嗅探是一种非常不完美的方法,无论您选择什么实现嗅探,随着时间的推移,它会变得不那么准确
    【解决方案2】:

    使用browser 宝石。您可以通过自定义 user_agent 检测浏览器。

    【讨论】:

    • 您知道 Google Chrome 的移动浏览器模拟器是否会使用该 gem 检测到 browser.mobile?
    • browser 很好,但需要 > ruby​​ 2。如果你被困在 1.9.3(像我一样),请查看 github.com/tscolari/mobylette
    • @JoeMorano 它确实可以在 Chrome 的模拟器中为我工作。
    • browser 似乎仍会在 2020 年得到维护,并且随着时间的推移只会增加使用量。
    【解决方案3】:

    application_helper.rb:

    def device
      agent = request.user_agent
      return "tablet" if agent =~ /(tablet|ipad)|(android(?!.*mobile))/i
      return "mobile" if agent =~ /Mobile/
      return "desktop"
    end
    

    然后你可以在你的视图中使用它:

    <% if device == "mobile" %>
      Show something for mobile users.
    <% end %>
    

    【讨论】:

      【解决方案4】:

      我建议查看 device_detector,它非常快速且易于部署。您只需将 user_agent 字符串传递给它,这可以使用 Rails 5 的 request.user_agent 来完成:

      @user_agent = request.user_agent
      
      @client = DeviceDetector.new(@user_agent)
      
      @client.device_type 
      

      注意:设备类型可以是以下之一:台式机、智能手机、平板电脑、控制台、便携式媒体播放器、电视、车载浏览器、相机

      https://github.com/podigee/device_detector

      【讨论】:

        【解决方案5】:

        您也可以通过 including &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; 上的 application.html.erb 标头标签来解决此问题

        只要您的网站是响应式的(例如使用 Bootstrap),您应该没问题。

        【讨论】:

        • 该问题旨在检查用户代理是否是移动设备。您的回答旨在实现响应式行为,这与问题意图大不相同。
        猜你喜欢
        • 2020-08-14
        • 1970-01-01
        • 2010-09-06
        • 2010-12-29
        • 2019-01-26
        • 2011-05-06
        • 2010-11-20
        相关资源
        最近更新 更多