检测Web浏览器或移动设备以显示链接。

4
我是一名Rails开发者,需要为移动端和普通浏览器用户展示不同的链接。例如,如果用户使用移动设备访问,我想显示以下内容:
<a href="instagram://user?username=<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a>

如果用户在浏览器上,我想显示:

如果用户在浏览器上,我希望展示:

<a href="http://instagram.com/<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a>

什么是最好的方式来做到这一点?谢谢
3个回答

10

浏览器数据以user_agent对象的形式呈现:

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
   helper_method :mobile?

   private

   def mobile? # has to be in here because it has access to "request"
      request.user_agent =~ /\b(Android|iPhone|iPad|Windows Phone|Opera Mobi|Kindle|BackBerry|PlayBook)\b/i
   end
end

这将允许您在视图中使用以下内容:

#app/views/controller/view.html.erb
<% if mobile? %>
   ... do something for mobile
<% else %>
   ... do something else
<% end %>

说实话,我不明白为什么有些人要硬编码他们的移动端界面。如果你正确使用CSS媒体查询,你不应该会遇到文件方面的问题,尽管你的情况显然需要服务器端条件。


0
我猜你想要实现深度链接。为此,我建议你使用deeplink.me。但是,如果你想按照Rails的方式来做,那么有一个名为browser的gem。以下代码将帮助你设置它。 Gemfile:
gem 'browser'

然后在你的

application_controller.rb:

class ApplicationController < ActionController::Base
  before_filter :get_browser

  def get_browser
    @browser = Browser.new(:ua => request.user_agent)
  end   
end

最后在你的视图中,你可以这样做:

<% if @browser.mobile? %>
   <a href="instagram://user?username=<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a>
<% else %>
  <a href="http://instagram.com/<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a>
<% end %>

太棒了,我要试一试! - fixulate

-3

我建议您使用像Bootstrap或Foundation这样的前端框架。这些框架可以让您适应移动设备和桌面设备的视图。


1
我正在使用Bootstrap,但我仍然需要确定它是否是移动设备以显示不同的链接...我认为需要更多细节来回答这个问题 :) - fixulate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接