Rails 4 uses application helpers inside initializers

Can I enable / use Application Helper methods inside config/initializers/browser_blocker.rb?

I use browser stone to detect and block old incompatible browsers.

Rails.configuration.middleware.use Browser::Middleware do
    include ApplicationHelper
    redirect_to :controller => 'error', :action => 'browser-upgrade-required' if browser_is_not_supported
end

The helper method I'm working with now:

  # 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
source share
2 answers

This is one way to do this:

# lib/browser_util.rb
module BrowserUtil
  def self.supported?(browser)
    # your code ...
  end
end

and wrap this 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 should not be in a separate module (BrowserUtil)

module ApplicationHelper
  def self.foo
    "FOO"
  end

  def foo
    ApplicationHelper.foo
  end
end

in using middleware

ApplicationHelper.foo

in views he would use the included method

foo
+6

, , , , - app, - . , , old_browser rails stack.

,

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
0

All Articles