matthewrudy / memoist

ActiveSupport::Memoizable with a few enhancements
MIT License
920 stars 99 forks source link

model_instance.reload doesn't flush cache #66

Open stevenspiel opened 7 years ago

stevenspiel commented 7 years ago

I would expect that calling #reload on an instance of an ActiveRecord model would flush the cache.

If I have a table named foos with one string column name:

class Foo < ActiveRecord::Base
  extend Memoist

  memoize def change_name!
    name = 'bar'
    save
    name
  end
end
describe Foo do
  describe '#change_name!' do
    subject { Foo.create(name: '') }

    expect { subject.change_name! }.to change { subject.reload.name }from('').to('bar')
  end
end

The above test fails unless #flush_cache is called on subject in the change block. Is this the intended behavior?

matthewrudy commented 7 years ago

@stevenspiel I agree this is surprising, and have at various times had solutions for this in my local projects.

As I remember there's no official callback for a reload so to make an instance variable be reset for a reload is a bit of a hack.

I wouldn't mind adding an opportunity optional module that could be prepended, or just add something to the docs.

Something like

module Memoist::ActiveRecordReloadable
  def reload
    flush_cache
    super
  end
end

MyModel.prepend(Memoist::ActiveRecordReloadable)