reference: ruby-journal.com
Install useragent gem by appending to Gemfile:
gem 'useragent'
then bundle install
Now we will inject a filter in ApplicationController to detect user agent. Below is the source code:
class ApplicationController < ActionController::Base
before_filter :check_browser
private
Browser = Struct.new(:browser, :version)
SupportedBrowsers = [
Browser.new('Safari', '6.0.2'),
Browser.new('Firefox', '19.0.2'),
Browser.new('Internet Explorer', '9.0'),
Browser.new('Chrome', '25.0.1364.160')
]
def check_browser
user_agent = UserAgent.parse(request.user_agent)
unless SupportedBrowsers.detect { |browser| user_agent >= browser }
render text: 'Your browser is not supported!'
end
end
end
Let’s digest what’s happening the code above.
Browsers is a Struct object with two attributes :browser and :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.