Posted about 10 years ago. Visible to the public. Deprecated.

Detect mobile or touch devices on both server and client

There is a better maintained regular expression to be found on

Although it's tempting flirt with detecting mobile/touch devices with CSS media queries or Javascript feature detection alone, this approach will be painful when heavily customizing a feature beyond just tweaking the looks. Eventually you will want want the same detection logic to be available on both server and client side.

This card shows how to get a Ruby method touch_device? for your Rails views and a method TouchDevice.isPresent() for your Javascripts.

Note that we are detecting touch devices by grepping the user agent, and the keyword list we are sniffing for sure is lacking many unpopular phones.

In your ApplicationHelper:

def touch_device? user_agent = request.headers["HTTP_USER_AGENT"] user_agent.present? && user_agent =~ /\b(Android|iPhone|iPad|Windows Phone|Opera Mobi|Kindle|BackBerry|PlayBook)\b/i end

In your layout:

%html %body{ :class => 'touch_device' => ('true' if touch_device?)}

In your application.js:

var TouchDevice = (function() { var presence = null; function isPresent() { if (_.isNull(presence)) { presence = $('body').is('.touch_device'); } return presence; } return { isPresent: isPresent }; })();

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Henning Koch
Last edit:
over 5 years ago
by Henning Koch
iphone, ipad, android
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more