Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect web-browser or mobile to display links

I am writing a rails application and need to present different links for mobile users to normal web browser users. For example, if the user is on a mobile 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 on 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

like image 559
fixulate Avatar asked Mar 15 '23 06:03

fixulate


1 Answers

Browser data comes in the form of the user_agent object:

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

Being honest, I don't get why people hard-code their mobile interface work. If you use CSS media queries properly, you shouldn't have an issue with the files, although your case certainly appears to require the server-side conditions.

like image 66
Richard Peck Avatar answered Mar 24 '23 15:03

Richard Peck