rails 4 use application helpers inside initializers

前端 未结 2 411
猫巷女王i
猫巷女王i 2021-01-21 10:37

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 b

2条回答
  •  臣服心动
    2021-01-21 11:26

    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
    

提交回复
热议问题