Skip to content

Instantly share code, notes, and snippets.

@oojikoo-gist
Last active August 29, 2015 14:19
Show Gist options
  • Save oojikoo-gist/6129771f9f4fc92becd6 to your computer and use it in GitHub Desktop.
Save oojikoo-gist/6129771f9f4fc92becd6 to your computer and use it in GitHub Desktop.
rails: block ie

reference: ruby-journal.com

How to Block Old IE Version With Rails

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment