Search code examples
ruby-on-railsrubyreloadautoloadzeitwerk

Zeitwerk needs to reload every change


In development enviroment, when using zeitwerk, every change in ruby code needs to restart the server, because zeitwerk isn't loading classes defined in mygem. I have a gem, used by my company that uses rails models. And some of that models are reopened, and we add some methods.

I have the following model in my app.

require_dependency("#{Mygem::Engine.root.join('app','models','identification.rb')}")

class Identification
  include Cacheable
  has_paper_trail

  def some method
  end
end

And the following model in mygem, path of my gem app/models/identification.rb:

class Identification < ApplicationRecord
  self.table_name = 'pub_identification'

  belongs_to :city, foreign_key: 'idcity'
end

But if I change anything in my code, I need restart my server, because model from my gems aren't reopened. I get the error:

undefined local variable or method `has_paper_trail' for Identification:Class

The has_paper_trail method is a method from mygem. And it only works if I restart. Any tips for this?

EDIT:

Gem Structure:

mygem/
├─ app/
│  ├─ models/
├─ config/
├─ lib/

Solution

  • You cannot have two files defining the same constant in the autoload paths.

    Your engine defines a model, and the application wants to decorate it. For this use case, please have a look at this documentation.