1

The mobile world changes almost daily. Expanding on http://scottwb.com/blog/2012/02/23/a-better-way-to-add-mobile-pages-to-a-rails-site/ which is sorta old -- what do you guys think of this mobile and tablet detection scheme?

Use case: The mobile and desktop versions of my Rails app are very different. Although they share the majority of views, JS and CSS (using media queries where applicable), there are cases where I need mobile-only and desktop-only views, JS and CSS.

Code changes

All tablets should be treated as mobile.

Above Android tablet thread mentions this for mobile:

  • /iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/

And this for tablet:

  • /ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/

I reckon, however, that only the below should be necessary?

  • /mobile|android|touch|webos|hpwos/

application_controller.rb

def mobile?
  if session[:mobile_override]
    session[:mobile_override] == "1"
  else
    request.user_agent.downcase =~ /mobile|android|touch|webos|hpwos/
  end
end
helper_method :mobile?

layout.html.erb

<% if mobile? %>
  <p>Mobile detected!</p>
<% end %>

application.js

var isMobile = false;

if(/mobile|android|touch|webos|hpwos/i.test(navigator.userAgent.toLowerCase())) {
  isMobile = true;
}

if(isMobile) {
  console.log('Mobile detected!')
}
Community
  • 1
  • 1
Mark Boulder
  • 13,577
  • 12
  • 48
  • 78

1 Answers1

2

Depending on your version of rails, you can do something like this...

before_action :set_variant

def set_variant
 request.variant = :tablet if request.user_agent =~ /iPad/
end

Then in your method do

respond_to do |format|
  format.html do |variant|
  variant.tablet # renders app/views/projects/show.html+tablet.erb
  variant.phone { extra_setup; render ... }
  variant.none  { special_setup } # executed only if there is no variant set
end

You will need a specific view for each names as app/views/projects/show.html+tablet.erb etc.

You can find all of this about half way down the page here

CWitty
  • 4,488
  • 3
  • 23
  • 40
  • Of course you need to tweak this to use the regex for the devices you want to check for. – CWitty Mar 17 '14 at 20:13
  • I'm in doubt, but I can't help but think that maybe my method above is simpler? Ie. no need for duplicate views, they all share the same `show.html.erb` but with a bunch of `<% if mobile? %>` in them. – Mark Boulder Mar 17 '14 at 20:41
  • You can definitely go that route. I am just showing you the official way rails supports. You said yourself that the views are very different for your desktop and mobile apps, I figured that this would give you the flexibility you need. – CWitty Mar 17 '14 at 20:44
  • Definitely an interesting approach. Thanks a lot. – Mark Boulder Mar 17 '14 at 20:46