[Ruby] How to get User Agent

Tadashi Shigeoka ·  Thu, March 8, 2012

I researched how to get User Agent in Ruby, so here’s a memo.

The User Agent itself is included in the request parameters.

Example of iPhone User Agent

request.env["HTTP_USER_AGENT"]
#=> Mozilla/5.0 (iPod; CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A405 Safari/7534.48.3

By checking the User Agent, you can redirect access from smartphones like iPhone or Android to smartphone-specific pages.

Sample filter to redirect to smartphone-specific site (Ruby on Rails)

before_filter :check_user_agent_for_mobile

def check_user_agent_for_mobile
  ua = request.env["HTTP_USER_AGENT"]
  if(ua.include?('Mobile') || ua.include?('Android'))
    redirect_to  :controller => "mobile", :action  => "index"
  end
end

All iPhone/iPad/iPod Touch devices have the string ‘Mobile’ in their User Agent, and Android devices have the string ‘Android’, so I wrote it this way.

User Agents are comprehensively listed on this website:

userAgent一覧/ユーザーエージェント一覧

That’s all.


Reference Information

Android携帯、タブレットをUser Agentで区別するRubyの正規表現|WEBデザイン Tips

That’s all from the Gemba.