Chr*_*ugh 2 ruby gem initialization ruby-on-rails
是否可以在?中包含/使用Application Helper方法config/initializers/browser_blocker.rb?
我正在使用浏览器gem来检测和阻止旧的非现代浏览器.
Rails.configuration.middleware.use Browser::Middleware do
include ApplicationHelper
redirect_to :controller => 'error', :action => 'browser-upgrade-required' if browser_is_not_supported
end
Run Code Online (Sandbox Code Playgroud)
我正在使用的助手方法:
# test browser version
def browser_is_not_supported
return true unless browser.modern?
return true if browser.chrome? && browser.version.to_i < ENV['BROWSER_BASE_VERSION_GOOGLE'].to_i
return true if browser.firefox? && browser.version.to_i < ENV['BROWSER_BASE_VERSION_FIREFOX'].to_i
return true if browser.safari? && browser.version.to_i < ENV['BROWSER_BASE_VERSION_SAFARI'].to_i
return true if browser.opera? && browser.version.to_i < ENV['BROWSER_BASE_VERSION_OPERA'].to_i
return true if browser.ie? && browser.version.to_i < ENV['BROWSER_BASE_VERSION_MSFT'].to_i
end
Run Code Online (Sandbox Code Playgroud)
这是一种方法:
# lib/browser_util.rb
module BrowserUtil
def self.supported?(browser)
# your code ...
end
end
Run Code Online (Sandbox Code Playgroud)
并从ApplicationHelper中包装它以在视图中使用
module ApplicationHelper
def is_browser_supported?
BrowserUtil.supported?(browser)
end
end
Run Code Online (Sandbox Code Playgroud)
在中间件中
Rails.configuration.middleware.use Browser::Middleware do
unless BrowserUtil.supported?(browser)
redirect_to :controller => 'error', :action => 'browser-upgrade-required'
end
end
Run Code Online (Sandbox Code Playgroud)
更新:它不需要在一个单独的模块(BrowserUtil)
module ApplicationHelper
def self.foo
"FOO"
end
def foo
ApplicationHelper.foo
end
end
Run Code Online (Sandbox Code Playgroud)
在中间件使用
ApplicationHelper.foo
Run Code Online (Sandbox Code Playgroud)
在视图中,它将使用包含的方法
foo
Run Code Online (Sandbox Code Playgroud)