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:
Next, I added two utility methods to app/controllers/application.rb:
# 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/126.96.36.199 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: