How to extend a mountable engine's model insid

2019-06-04 19:30发布

问题:

Using Rails 3.2.2 and Ruby 1.9.2.

I have a rails mountable engine EngineA that declares a User class inheriting form ActiveRecord::Base. I have another engine EngineB that wants to inject functionality into EngineA::User. Right now what I have done is shown below:

Method 1:

#EngineA app/models/engine_a/user.rb
module EngineA
  class User < ActiveRecord::Base
    has_attached_file :avatar
    has_many :somethings
  end
end

#EngineB lib/engine_b/user.rb
module EngineB
  module User
    def self.extended obj
      obj.class_eval do
        has_many :something_elses
      end
    end
  end
end

EngineA::User.extend EngineB::User

This gives me an uninitialized constant EngineA::User error. Even when I require that specific file I run into the problem of EngineA needing paperclip so that has_attached_file is understood. That road ended when I realized I would have to know and require the dependencies for EngineA inside EngineB.

Method 2:

I used the same code as before except I removed the last line EngineA::User.extend EngineB::User from the EngineB user.rb file. I then moved that call to an initializer inside EngineB.

#EngineB config/initializers/my_mixin.rb
EngineA::User.extend EngineB::User

This worked perfectly!!! Except in development mode when I would change code and the models would refresh. The only thing that was refreshed was the EngineA::User and not the mixin that I had put as an initializer. So once I changed code, I lost all of my extended functionality.

I'm not even positive this is the most 'efficient' way to do this... any help would be greatly appreciated. Thanks in advance.

回答1:

According to the configuration documentation, you can use an ActionDispatch callback to load items. These callbacks will run when at every request if cache_classes is set to false, like in development mode.

Inside of your EngineB.rb file, you might try something like this:

if Rails.env.development?
    ActionDispatch::Callbacks.to_prepare do
        load "#{File.expand_path(File.dirname(__FILE__))}/../config/initializers/my_mixin.rb"
    end
end