Rack::UserAgent

Rack Middleware for filtering by user agent

Use

Let’s say you don’t support IE6 and want to prevent IE6 users from accessing to your Rails app. You’re in luck. Just add this to your config/environment.rb:

config.gem "bebanjo-rack-useragent", :lib => "rack/user_agent", :source => "http://gems.github.com"

config.middleware.use "Rack::UserAgent::Filter", [
  {:browser => "Internet Explorer", :version => "7.0"}
]

And, of course, install the gem:

$ [sudo] rake gems:install

Done! From now on users with IE version lower than 7.0 will get a nice error message saying that their browsers need to be updated… Ok, ok, not so nice message, you can personalize it by putting an upgrade.html file inside the /public directory of your application.

- Hey, I need to show localized versions of the message to my french and spanish users!

No problem, just add upgrade.es.html and upgrade.fr.html to /public (Note that rack.locale env variable needs to be previously set for this to work. Rack::Locale in rack-contrib can do that for you)

- Cool!, what about something more dynamic… like ERB?

Granted! You’ll have to add to the config which template to use. In environment.rb:

config.middleware.use "Rack::UserAgent::Filter", [
  {:browser => "Internet Explorer", :version => "7.0"}
], :template => "#{RAILS_ROOT}/app/views/shared/upgrade.html.erb"

Then you could show the browser version as part of your message:

Sorry but <%= "#{@browser.browser} #{@browser.version}" %> is not supported

- Can I use it with non-Rails Rack frameworks, like Sinatra?

Sure. You only have to take into account that you’ll always have to set which template to use. i.e: In config.ru:

require 'rack/user_agent'

use Rack::UserAgent::Filter, [
  {:browser => "Internet Explorer", :version => "7.0"}
], :template => File.dirname(__FILE__) + "/public/upgrade.html"

Enjoy it!

Authors

Contributors

We’re looking forward for your patches. Fork us!

Copyright © 2008-2015 BeBanjo, released under the MIT license