diff --git a/lib/esse/document.rb b/lib/esse/document.rb index bb663d5..e3ee53c 100644 --- a/lib/esse/document.rb +++ b/lib/esse/document.rb @@ -109,10 +109,10 @@ def document_for_partial_update(source) end def inspect - attributes = %i[id routing source].map do |attr| - value = send(attr) + attributes = {id: :id, routing: :routing, source: :memoized_source}.map do |attr_name, attr_src| + value = send(attr_src) next unless value - "#{attr}: #{value.inspect}" + "#{attr_name}: #{value.inspect}" rescue nil end.compact.join(', ') @@ -131,9 +131,17 @@ def mutations end def mutated_source - return source unless @__mutations__ + return memoized_source unless @__mutations__ - @__mutated_source__ ||= source.merge(@__mutations__) + @__mutated_source__ ||= memoized_source.merge(@__mutations__) + end + + protected + + def memoized_source + return @__memoized_source__ if defined?(@__memoized_source__) + + @__memoized_source__ = source || {} end end end diff --git a/spec/esse/document_spec.rb b/spec/esse/document_spec.rb index af0da6b..18f9609 100644 --- a/spec/esse/document_spec.rb +++ b/spec/esse/document_spec.rb @@ -133,6 +133,23 @@ def source expect(document.to_bulk(data: true)).to eq(_id: 1, _type: 'foo', routing: 'bar', timeout: 10, data: {}) end end + + context 'when the document source is not memoized' do + before do + document_class.class_eval do + def source + { foo: SecureRandom.hex } + end + end + end + + it 'memoizes the source' do + data1 = document.to_bulk(data: true)[:data] + expect(document.to_bulk(data: true)[:data]).to eq(data1) + data2 = document.to_bulk(data: true)[:data] + expect(data1).to be(data2) + end + end end describe '#doc_header' do