Skip to content

Commit e6c11eb

Browse files
authored
Merge pull request #505 from gocardless/504-last_transition-cache-doesnt-work-for-newly-created-objects
Make sure `nil` is accepted as cached value
2 parents bb9283e + 8b8a9bb commit e6c11eb

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

lib/statesman/adapters/active_record.rb

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def create(from, to, metadata = {})
5252

5353
raise
5454
ensure
55-
@last_transition = nil
55+
remove_instance_variable(:@last_transition)
5656
end
5757

5858
def history(force_reload: false)
@@ -65,18 +65,18 @@ def history(force_reload: false)
6565
end
6666
end
6767

68-
# rubocop:disable Naming/MemoizedInstanceVariableName
6968
def last(force_reload: false)
7069
if force_reload
7170
@last_transition = history(force_reload: true).last
71+
elsif instance_variable_defined?(:@last_transition)
72+
@last_transition
7273
else
73-
@last_transition ||= history.last
74+
@last_transition = history.last
7475
end
7576
end
76-
# rubocop:enable Naming/MemoizedInstanceVariableName
7777

7878
def reset
79-
@last_transition = nil
79+
remove_instance_variable(:@last_transition)
8080
end
8181

8282
private

spec/statesman/adapters/active_record_spec.rb

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -308,9 +308,9 @@
308308
described_class.new(MyActiveRecordModelTransition, model, observer)
309309
end
310310

311-
before { adapter.create(:x, :y) }
312-
313311
context "with a previously looked up transition" do
312+
before { adapter.create(:x, :y) }
313+
314314
before { adapter.last }
315315

316316
it "caches the transition" do
@@ -376,6 +376,16 @@
376376
expect(adapter.last.to_state).to eq("y")
377377
end
378378
end
379+
380+
context "without previous transitions" do
381+
it "does query the database only once" do
382+
expect(model.my_active_record_model_transitions).
383+
to receive(:order).once.and_call_original
384+
385+
expect(adapter.last).to eq(nil)
386+
expect(adapter.last).to eq(nil)
387+
end
388+
end
379389
end
380390

381391
it "resets last with #reload" do

0 commit comments

Comments
 (0)