问题
Is it possible to include / use Application Helper methods inside of an config/initializers/browser_blocker.rb
?
I am using the browser gem to detect and block older non modern browsers.
Rails.configuration.middleware.use Browser::Middleware do
include ApplicationHelper
redirect_to :controller => 'error', :action => 'browser-upgrade-required' if browser_is_not_supported
end
Helper method I am currently working with:
# 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
回答1:
This is one way to do it:
# lib/browser_util.rb
module BrowserUtil
def self.supported?(browser)
# your code ...
end
end
and wrap that from ApplicationHelper for use in views
module ApplicationHelper
def is_browser_supported?
BrowserUtil.supported?(browser)
end
end
in middleware
Rails.configuration.middleware.use Browser::Middleware do
unless BrowserUtil.supported?(browser)
redirect_to :controller => 'error', :action => 'browser-upgrade-required'
end
end
UPDATE: it does not need to be in a separate module (BrowserUtil)
module ApplicationHelper
def self.foo
"FOO"
end
def foo
ApplicationHelper.foo
end
end
in middleware use
ApplicationHelper.foo
in views it would use the included method
foo
回答2:
Ofcourse you can but that's bad idea, i agree with that that logic supposed to somewhere in app
but sometime you have to deal with it. I am saying this because you can block the request before old_browser
request gets it and load rails stack
.
Anyway, this is how can you can do it
Rails.configuration.middleware.use Browser::Middleware do
self.class.send(:include,ApplicationHelper)
redirect_to :controller => 'error', :action => 'browser-upgrade-required' unless browser_is_supported?
end
来源:https://stackoverflow.com/questions/23035947/rails-4-use-application-helpers-inside-initializers