For anyone who has ever done any sort of web development, there comes a point where you need to make sure what you are building works the same across all browser types and versions … or at least the major ones. If you’ve ever spent any time tweaking your code and fighting with the different browser types, you know that Microsoft has done its best to annoy the shit out of you once again with Internet Explorer. Because it does not adhere to web standards, it always seems to cause trouble when compared to Firefox or Safari. The spacing is a bit different, and what really bit me this time was a freakish bug in which a background image url will disappear when scrolling, or in my case, I was hiding a DIV and then making it appear with a javascript toggle. [SIDE NOTE: The scriptaculous javascript classes for Ruby are FANTABULOUS! So much fun to code and instant gratification because you can see spiffy results super fast!] I found some great information on common IE css bugs and some possible fixes for them. In my scenario, I had to change my code for IE, to accommodate the browser’s inadequacies. I started looking at javascript browser sniffers, but then realized that Ruby on Rails provides a quick and easy way to get the information I needed for a browser check. The request.user_agent object, contains information on the client’s browser type, version, and even operating system type!
<%= request.user_agent %> #=> Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1
So, if I need to adjust my code for IE, all I have to do is check for "MSIE" as part of the string:
<% if !(request.user_agent.include? "MSIE") %>
… regular code here …
<% else %>
…. stupid IE code here ….
<% end %>
I didn’t want to compromise the design of my site, by changing the code across all browsers. I wanted to keep my hidden DIV with the fancy pants javascript toggle for all the user’s who aren’t stuck on IE. Now, the IE users will get the DIV displayed immediately, while all other browsers will have a cleaner user experience, with the hidden DIV, only appearing when they want it to.
Thank goodness for Ruby, in making this browser check so easy!! The other solutions I found required a nice chunk of javascript with a technique called browser sniffing. The other way to do it, is by checking what objects or features are implemented by the browser that is hitting the site. There is a good write up for determining browser type using object detection, with a chart that shows what objects/features set the different browsers apart. OR …. you can make a simple Ruby call to the request.user_agent object …. SO EASY!!!! This is the kind of thing that makes coding with Ruby on Rails such a pleasurable experience!!!