contentful / contentful_model

A lightweight wrapper around the Contentful api gem, to make it behave more like ActiveRecord
MIT License
44 stars 42 forks source link

Rails: Support reloading of classes in development #122

Open pfeiffer opened 6 years ago

pfeiffer commented 6 years ago

At the moment changing a method in a class descending from ContentfulModel::Base requires full reload of Rails environment.

Example:

class TestModel < ContentfulModel::Base
   self.content_type_id = 'test'

   def title
      "This is the title!"
   end
end
# eg. in "rails console"
irb(main):001:0> TestModel.first.title
=> "This is the title!"

Changing the #title method:

....
def title
   "New title?"
end
....

And then reloading:

irb(main):002:0> reload!
Reloading...
=> true

irb(main):003:0> TestModel.first.title
=> "This is the title!" # Would have expected "New title?" here
dlitvakb commented 6 years ago

Hey @pfeiffer,

I'n not entirely sure on what I could do to support this. Would you mind helping with the implementation?

Cheers

mrGrazy commented 5 years ago

The problem that is breaking reloading is that mappings are not readded if the class is redefined: https://github.com/contentful/contentful_model/blob/b286afd939daae87fdeb1f320f43753dcaae3144/lib/contentful_model/base.rb#L123

If I override this method to return false, the class gets reloaded fine in development.

class TestModel < ContentfulModel::Base
   # ....
  def self.mapping?
    false
  end
end

This happens because the rails environment persists class variables like entry_mapping, and that mapping contains a reference to the old version of the model.

I don't know if that helps.

timfjord commented 5 years ago

Here is how this problem can be fixed

module MyApp
  class Application < Rails::Application
    config.to_prepare do
      ContentfulModel.configuration.entry_mapping.each do |content_type_id, model|
        ContentfulModel.configuration.entry_mapping[content_type_id] = Object.const_get(model.to_s)
      end
    end
  end
end

It is still an expiemintal solution I am keeping an eye on it in my current project. And if it will work I will send a PR with a more generic fix

arielkirkwood commented 3 years ago

@dlitvakb Do you still need more information in order to understand how to improve this? This has been one of the most frustrating parts of using this library :(