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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With