Detecting a web browser or mobile device to display links

I am writing an application for rails and should provide different links for mobile users to regular web browser users. For example, if the user is on a mobile device, I want to display:

<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>

If the user is in a browser, I want to display:

<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>

What is the best way to do this? Thanks

+4
source share
3 answers

Browser data is presented as an object 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

This will allow you to use the following in your views:

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

, , . CSS, , , , .

+6

, . deeplink.me. , , browser. .

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 %>
0

I suggest you use external work like Bootstrap or Foundation. This framework allows you to focus on both mobile views and the desktop.

-2
source

Source: https://habr.com/ru/post/1614215/


All Articles