fixulate
fixulate

Reputation: 371

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

Upvotes: 4

Views: 2894

Answers (3)

Richard Peck
Richard Peck

Reputation: 76774

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.

Upvotes: 11

usmanali
usmanali

Reputation: 2036

I am guessing that you want to achieve deep linking. For that I would suggest you to use deeplink.me. However if you want to do it the rails way, then there is a gem named browser. Following code will help you set it up.

Gemfile:

gem 'browser'

then in your

application_controller.rb:

class ApplicationController < ActionController::Base
  before_filter :get_browser

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

and finally in your views, you can do:

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

Upvotes: 0

Navraj Nat
Navraj Nat

Reputation: 1

I suggest you use a front-end work like Bootstrap or Foundation. Those frameworks allow you to orient to both mobile views and desktop views.

Upvotes: -3

Related Questions