Detect Mobile Device with Ruby for Sinatra/Rails
12 Jan 2011
Tags: ruby sinatra ruby detect mobile device mobile mobile device redirect mobile githubUPDATE: Changed the code to reflect correction of a bug
So I’ve been working on a new mobile site/app in Sinatra/Ruby on Heroku. The issue I’ve had is finding a good script to detect mobile devices. Turned out there is a gem for rails called mobile-fu by Brendan Lim on Github.
While I did not need a gem, I was able to find in the code he created the following string:
MOBILE_USER_AGENTS = 'palm|blackberry|nokia|phone|midp|mobi|symbian|chtml|ericsson|minimo|audiovox|motorola|samsung|telit|upg1|windows ce|ucweb|astel|plucker|x320|x240|j2me|sgh|portable|sprint|docomo|kddi|softbank|android|mmp|pdxgw|netfront|xiino|vodafone|portalmmm|sagem|mot-|sie-|ipod|up.b|webos|amoi|novarra|cdm|alcatel|pocket|ipad|iphone|mobileexplorer|mobile’
(that’s all one bis string by the way)
I wrote this method to return a true/false of whether or not it is a mobile device:
def is_mobile_device?(agent)
if (agent =~ Regexp.new(MOBILE_USER_AGENTS)).blank?
return false
else
return true
end
end
So far it detects all the devices with my own testing platform, so I think it is working right. Hope this helps anyone else that was looking for a solution for this problem :)