Search code examples
ruby-on-railsrubyruby-on-rails-pluginsruby-on-rails-2

How to extend a model in a Rails engine from another Rails engine?


I think the simplest way to explain this is with a contrived example. I am using Rails 2.3.8 with Ruby 1.8.7 and ActiveRecord to MySQL db.

I have the following (contrived) model in one engine (installed in vendor/plugins directory of main app):

# contrived_app/vendor/plugins/concerts_engine/app/models/
class Concert < ActiveRecord::Base
  has_many :artists
  belongs_to :venue
end

And the following (contrived) model in another engine:

# contrived_app/vendor/plugins/tickets_engine/app/models/
class Ticket < ActiveRecord::Base
  belongs_to :concert
end

How can I include/extend

  has_many :tickets

in the Concert model?

Also, is the load order important, and if so what happens if the Concert model hasn't been defined/loaded yet?

Is it possible to only include

  belongs_to :concert

if Concert been defined?


Solution

  • Turns out I can do the following in the tickets_engine:

    # contrived_app/vendor/plugins/tickets_engine/config/initializers/concert_extensions.rb
    # or
    # contrived_app/config/initializers/concert_extensions.rb
    Rails.logger.info "\n~~~ Loading extensions to the Concert model from #{__FILE__}\n"
    
    Concert.class_eval do
      has_many :tickets
    end
    

    Personally, my preferred method is to extend the concert model from the tickets_engine, but load order and dependencies are important. i.e. tickets_engine would need to add a dependency on the concerts_engine in it's gemspec, and concert_engine would need to be loaded before tickets_engine.