Skip to content

Commit 50fee81

Browse files
kkirschekarmi
authored andcommitted
[STORE] Short-circuit the operation and return false when the model is not valid
Closes elastic#289
1 parent ee0af92 commit 50fee81

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

elasticsearch-persistence/lib/elasticsearch/persistence/model/store.rb

+3
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,9 @@ def destroy(options={})
102102
# @return [Hash] The Elasticsearch response as a Hash
103103
#
104104
def update(attributes={}, options={})
105+
unless options.delete(:validate) == false
106+
return false unless valid?
107+
end
105108
raise DocumentNotPersisted, "Object not persisted: #{self.inspect}" unless persisted?
106109

107110
run_callbacks :update do

elasticsearch-persistence/test/unit/model_store_test.rb

+37
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,43 @@ def valid?; false; end;
311311
assert subject.update( {}, { script: 'EXEC' } )
312312
end
313313

314+
should "not update an invalid model" do
315+
subject.expects(:persisted?).returns(true)
316+
subject.expects(:id).returns('abc123').at_least_once
317+
318+
@gateway
319+
.expects(:update)
320+
.never
321+
322+
subject.instance_eval do
323+
def valid?; false; end;
324+
end
325+
326+
assert ! subject.update
327+
assert ! subject.persisted?
328+
end
329+
330+
should "skip the validation with the :validate option" do
331+
subject.expects(:persisted?).returns(true)
332+
subject.expects(:id).returns('abc123').at_least_once
333+
334+
@gateway
335+
.expects(:update)
336+
.with do |object, options|
337+
assert_equal subject, object
338+
assert_equal nil, options[:id]
339+
true
340+
end
341+
.returns({'_id' => 'abc123'})
342+
343+
subject.instance_eval do
344+
def valid?; false; end;
345+
end
346+
347+
assert subject.update validate: false
348+
assert subject.persisted?
349+
end
350+
314351
should "pass the options to gateway" do
315352
subject.expects(:persisted?).returns(true)
316353

0 commit comments

Comments
 (0)