Extending controllers of a Rails 3 Engine in the main app

后端 未结 7 950
执念已碎
执念已碎 2020-11-30 02:52

I am using a Rails engine as a gem in my app. The engine has PostsController with a number of methods and I would like to extend the controller logic in my main

7条回答
  •  星月不相逢
    2020-11-30 03:07

    You can use Ruby's send() method to inject your code into the controller at the time the engine is created...

    # lib/cool_engine/engine.rb
    
    module CoolEngine
      class Engine < ::Rails::Engine
    
        isolate_namespace CoolEngine
    
        initializer "cool_engine.load_helpers" do |app|
          # You can inject magic into all your controllers...
          ActionController::Base.send :include, CoolEngine::ActionControllerExtensions
          ActionController::Base.send :include, CoolEngine::FooBar
    
          # ...or add special sauce to models...
          ActiveRecord::Base.send :include, CoolEngine::ActiveRecordExtensions
          ActiveRecord::Base.send :include, CoolEngine::MoreStuff
    
          # ...even provide a base set of helpers
          ApplicationHelper.send :include, CoolEngine::Helpers
        end
      end
    end
    

    This method spares you from having to redefine the controller inheritance within your main app.

提交回复
热议问题