Skip to content

Instantly share code, notes, and snippets.

@jsugarman
Created April 21, 2017 19:57
Show Gist options
  • Save jsugarman/84a8b9d36a23b5cfb7d996f059874662 to your computer and use it in GitHub Desktop.
Save jsugarman/84a8b9d36a23b5cfb7d996f059874662 to your computer and use it in GitHub Desktop.
Blacklist user agents controller concern
module UserAgentHelper
extend ActiveSupport::Concern
Browser = Struct.new(:browser, :version)
SUPPORTED_BROWSER_BLACKLIST = [
Browser.new(UserAgent::Browsers::InternetExplorer.new.browser, UserAgent::Version.new('7.0'))
].freeze
included do
helper_method :unsupported_browser?, :user_agent
def user_agent
@ua ||= UserAgent.parse(request.user_agent)
end
def supported_browser?
SUPPORTED_BROWSER_BLACKLIST.none? do |black_listed_user_agent|
user_agent <= black_listed_user_agent
end
end
def unsupported_browser?
!supported_browser?
end
end
end
@jsugarman
Copy link
Author

jsugarman commented Apr 21, 2017

To blacklist particular browser versions in rails. Place the above concern in app/controllers/concerns/user_agent_helper.rb and include UserAgentHelper in whichever controller you need it. You can then use if unsupported_browser? to conditionally display a warning, flash or whatever in the controller or a view.

To blacklist further browsers/user_agents just add a new element to the SUPPORTED_BROWSER_BLACKLIST constant.
e.g.

Browser.new(UserAgent::Browsers::InternetExplorer.new.browser, UserAgent::Version.new('7.0'))

see useragent gem for ::Browsers you can specify (you can just use a string instead). For the version comparison to function you must use UserAgent::Version.new('n[.n.[n]]'), rather than a string, for the version attribute.

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