Rails 3.1: Better way to expose an engine's helper within the client app

后端 未结 5 1854
夕颜
夕颜 2020-12-08 10:22

I have found a few articles addressing the issue of helpers within an engine not being accessible to the consuming (parent) application. To make sure we are all on the same

相关标签:
5条回答
  • 2020-12-08 10:42

    You can create an initializer to accomplish this like so:

    module MyEngine
      class Engine < Rails::Engine
        initializer 'my_engine.action_controller' do |app|
          ActiveSupport.on_load :action_controller do
            helper MyEngine::ImportantHelper
          end
        end
      end
    end
    
    0 讨论(0)
  • 2020-12-08 10:43

    If you want to keep the code in the engine, instead of every implementing application, use this:

    module MyEngine
      class Engine < Rails::Engine
        isolate_namespace MyEngine
    
        config.to_prepare do
          MyEngine::ApplicationController.helper Rails.application.helpers
        end
    
      end
    end
    
    0 讨论(0)
  • 2020-12-08 10:44

    I have written two blog posts about creating engines from scratch, and following them everything should work as expected (without additional configurations needed). Maybe you are still interested in:

    • Rails 3.1 Engines: Part I – The engine
    • Rails 3.1 Engines: Part II – The gem
    • Rails 3.1 Engines: Part III – The environment

    Update: It's three articles in the meantime, and there's still some info to come. Please give me feedback.

    0 讨论(0)
  • 2020-12-08 10:49

    Include this code in engine.rb is also be very helpful

    config.before_initialize do
      ActiveSupport.on_load :action_controller do
        helper MyEngine::Engine.helpers
      end
    end
    

    Basically your engine would look like

    module MyEngine
      class Engine < Rails::Engine
        isolate_namespace MyEngine
    
        # Here comes the code quoted above 
    
      end
    end
    
    0 讨论(0)
  • 2020-12-08 11:05
    module YourEngine
      module Helpers
        def a_helper
        end
    
        ...
      end
    end
    
    ActionController::Base.send(:helper, YourEngine::Helpers)
    
    0 讨论(0)
提交回复
热议问题