Commit ca1aafee authored by Markus Koller's avatar Markus Koller

Allow passing a block to safe_find_or_create_by

parent c2155083
......@@ -42,15 +42,15 @@ class ApplicationRecord < ActiveRecord::Base
limit(count)
end
def self.safe_find_or_create_by!(*args)
safe_find_or_create_by(*args).tap do |record|
def self.safe_find_or_create_by!(*args, &block)
safe_find_or_create_by(*args, &block).tap do |record|
record.validate! unless record.persisted?
end
end
def self.safe_find_or_create_by(*args)
def self.safe_find_or_create_by(*args, &block)
safe_ensure_unique(retries: 1) do
find_or_create_by(*args)
find_or_create_by(*args, &block)
end
end
......
......@@ -38,6 +38,14 @@ RSpec.describe ApplicationRecord do
expect { Suggestion.safe_find_or_create_by(build(:suggestion).attributes) }
.to change { Suggestion.count }.by(1)
end
it 'passes a block to find_or_create_by' do
attributes = build(:suggestion).attributes
expect do |block|
Suggestion.safe_find_or_create_by(attributes, &block)
end.to yield_with_args(an_object_having_attributes(attributes))
end
end
describe '.safe_find_or_create_by!' do
......@@ -51,6 +59,14 @@ RSpec.describe ApplicationRecord do
it 'raises a validation error if the record was not persisted' do
expect { Suggestion.find_or_create_by!(note: nil) }.to raise_error(ActiveRecord::RecordInvalid)
end
it 'passes a block to find_or_create_by' do
attributes = build(:suggestion).attributes
expect do |block|
Suggestion.safe_find_or_create_by!(attributes, &block)
end.to yield_with_args(an_object_having_attributes(attributes))
end
end
describe '.underscore' do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment