Skip to content

Commit

Permalink
Merge pull request #505 from gocardless/504-last_transition-cache-doe…
Browse files Browse the repository at this point in the history
…snt-work-for-newly-created-objects

Make sure `nil` is accepted as cached value
  • Loading branch information
zerc authored Apr 3, 2023
2 parents bb9283e + 8b8a9bb commit e6c11eb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
10 changes: 5 additions & 5 deletions lib/statesman/adapters/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
14 changes: 12 additions & 2 deletions spec/statesman/adapters/active_record_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit e6c11eb

Please sign in to comment.