diff --git a/lib/statesman/adapters/active_record.rb b/lib/statesman/adapters/active_record.rb index 90d31bbc..5847bd9a 100644 --- a/lib/statesman/adapters/active_record.rb +++ b/lib/statesman/adapters/active_record.rb @@ -52,7 +52,7 @@ def create(from, to, metadata = {}) raise ensure - @last_transition = nil + remove_instance_variable(:@last_transition) end def history(force_reload: false) @@ -65,18 +65,18 @@ def history(force_reload: false) end end - # rubocop:disable Naming/MemoizedInstanceVariableName def last(force_reload: false) if force_reload @last_transition = history(force_reload: true).last + elsif instance_variable_defined?(:@last_transition) + @last_transition else - @last_transition ||= history.last + @last_transition = history.last end end - # rubocop:enable Naming/MemoizedInstanceVariableName def reset - @last_transition = nil + remove_instance_variable(:@last_transition) end private diff --git a/spec/statesman/adapters/active_record_spec.rb b/spec/statesman/adapters/active_record_spec.rb index 0cb7d42d..0b155536 100644 --- a/spec/statesman/adapters/active_record_spec.rb +++ b/spec/statesman/adapters/active_record_spec.rb @@ -308,9 +308,9 @@ described_class.new(MyActiveRecordModelTransition, model, observer) end - before { adapter.create(:x, :y) } - context "with a previously looked up transition" do + before { adapter.create(:x, :y) } + before { adapter.last } it "caches the transition" do @@ -376,6 +376,16 @@ expect(adapter.last.to_state).to eq("y") end end + + context "without previous transitions" do + it "does query the database only once" do + expect(model.my_active_record_model_transitions). + to receive(:order).once.and_call_original + + expect(adapter.last).to eq(nil) + expect(adapter.last).to eq(nil) + end + end end it "resets last with #reload" do