Rails engines extending functionality

前端 未结 6 757
夕颜
夕颜 2020-12-01 06:50

I have an engine which defines some models and controllers. I want to be able to extend functionality of some models/controllers in my application (eg. adding methods) witho

6条回答
  •  时光取名叫无心
    2020-12-01 07:32

    You can add these lines to you engine's module file in the lib root directory:

    def self.root
      File.expand_path(File.dirname(File.dirname(__FILE__)))
    end
    
    def self.models_dir
      "#{root}/app/models"
    end
    
    def self.controllers_dir
      "#{root}/app/controllers"
    end
    

    Then you have the ability in the main application (the app making use of the engine) to require the necessary files from the engine. This is nice because you maintain Rails Engines default functionality and also have an easy tool for making use of normal ruby inheritance, without the need for patching.

    EX:

    #ENGINE Model -
    
    class User < ActiveRecord::Base
      def testing_engine
        puts "Engine Method"  
      end
    end
    
    #MAIN APP Model -
    
    require "#{MyEngine.models_dir}/user"
    class User
      def testing_main_app
        puts "Main App Method"  
      end
    end
    
    #From the Main apps console
    
    user = User.new
    
    puts user.testing_engine #=>  "Engine Method"
    
    puts user.tesing_main_app #=> "Main App Method"
    

提交回复
热议问题