lib/esse/document.rb in esse-0.2.6 vs lib/esse/document.rb in esse-0.3.0

- old
+ new

@@ -63,15 +63,17 @@ hash[:_routing] = routing if routing hash.merge!(meta) end end - def to_bulk(data: true) - { _id: id }.tap do |h| - h[:data] = source&.to_h if data - h[:_type] = type if type - h[:routing] = routing if routing? + def to_bulk(data: true, operation: nil) + doc_header.tap do |h| + if data && operation == :update + h[:data] = { doc: source_with_lazy_attributes } + elsif data + h[:data] = source_with_lazy_attributes + end h.merge!(meta) end end def ignore_on_index? @@ -84,8 +86,39 @@ def ==(other) other.is_a?(self.class) && ( id == other.id && type == other.type && routing == other.routing && meta == other.meta && source == other.source ) + end + + def doc_header + { _id: id }.tap do |h| + h[:_type] = type if type + h[:_routing] = routing if routing? + end + end + + def inspect + attributes = %i[id routing source].map do |attr| + value = send(attr) + "#{attr}: #{value.inspect}" if value + end.compact.join(', ') + "#<#{self.class.name || 'Esse::Document'} #{attributes}>" + end + + protected + + def source_with_lazy_attributes + return source unless @__lazy_source_data__ + + @__lazy_source_data__.merge(source) + end + + # api private + def __add_lazy_data_to_source__(hash) + return hash unless hash.is_a?(Hash) + + @__lazy_source_data__ ||= {} + @__lazy_source_data__.merge!(hash) end end end