Created
April 21, 2017 19:57
-
-
Save jsugarman/84a8b9d36a23b5cfb7d996f059874662 to your computer and use it in GitHub Desktop.
Blacklist user agents controller concern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To blacklist particular browser versions in rails. Place the above concern in
app/controllers/concerns/user_agent_helper.rb
andinclude UserAgentHelper
in whichever controller you need it. You can then useif 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.
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.