This applies for Rails > 2.x
How does thing work?
When you surf the site, your browser name and versions are stored in
HTTP_USER_AGENT in the request. We need to process this string to work out the browser version and name to decide to greet viewers with warning text or not.
We will use
request.user_agent to grab the
HTTP_USER_AGENT string. An example of user agent string:
With a bit of text processing, we could work out the browser version, OS platform. Sound simple, isn’t it? A bit of regex magic and you could write your own detect method. However, we will not do reinvent the wheel in this tutorial, instead we will use the
useragent gem for the sake of convenience.
useragent gem by appending to
Now we will inject a filter in
ApplicationController to detect user agent. Below is the source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Let’s digest what’s happening the code above.
Browsers is a
Struct object with two attributes
:version. This models after the way
UserAgent create browser object. Pay attention to
SupportedBrowsers closely, this array defines a stack of supported browsers.
check_browser will get called before any action, this method compare your current user agent with
SupportedBrowsers. If the condition is not met, we render a simple text to warn the user. You could extend it to use HTML template if you like.
Please be noted that I assume all your controllers are subclass of
ApplicationController. Please adapt the source code accordingly should your controllers extends different parent controller class.