Once in a while, even a blind squirrel finds a nut.
Different Content in Rails Based on UserAgent
I was recently working on a website built using Rails that needed to render different content for certain user agents. Specifically, we needed simpler versions of certain pages for BlackBerry devices. Here’s how I accomplished it.
First, I added a new mime-type for BlackBerry by adding the following line to config/initializers/mime_types.rb:
mime_types.rb
1
Mime::Type.register_alias"text/html",:blackberry
Next, I added two utility methods to app/controllers/application.rb:
application.rb
123456789101112131415161718192021
# Checks UserAgentdefis_blackberry?ua=request.user_agentreturnfalseifua.nil?returnfalseif!ua.downcase.index('blackberry')# Don't call the BlackBerry 9800 a BlackBerry, since it has a modern browser# based on WebKit:# Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/6.0.0.141 Mobile Safari/534.1+returnfalseifua.downcase.index('webkit')# Must be a BlackBerry!trueend# Sets the respond_to format to blackberry if blackberrydefset_blackberry_formatif!request.xhr?&&is_blackberry?request.format=:blackberryendend
With that in hand, it’s easy to render BlackBerry specific content on specific pages: