lib/nazrin/searchable.rb in nazrin-2.5.0 vs lib/nazrin/searchable.rb in nazrin-2.6.0

- old
+ new

@@ -1,9 +1,11 @@ require 'active_support/concern' module Nazrin module Searchable + class InvalidBatchOperationError < StandardError; end + extend ActiveSupport::Concern included do alias_method :delete_from_index, :nazrin_delete_from_index unless method_defined? :delete_from_index alias_method :add_to_index, :nazrin_add_to_index unless method_defined? :add_to_index @@ -25,10 +27,11 @@ module ClassMethods def self.extended(base) class << base alias_method :search, :nazrin_search unless method_defined? :search alias_method :searchable, :nazrin_searchable unless method_defined? :searchable + alias_method :batch_operation, :nazrin_batch_operation unless method_defined? :batch_operation alias_method :fields, :nazrin_fields unless method_defined? :fields alias_method :field, :nazrin_field unless method_defined? :field alias_method :searchable_configure, :nazrin_searchable_configure unless method_defined? :searchable_configure end end @@ -43,9 +46,31 @@ class_variable_set( :@@nazrin_doc_client, Nazrin::DocumentClient.new(nazrin_searchable_config)) class_variable_set(:@@nazrin_search_field_data, {}) block.call + end + + def nazrin_batch_operation(type_objects_mapping) + operations = type_objects_mapping.each_with_object({}) do |(type, objects), hash| + case type.to_sym + when :add + hash[:add] = objects.map do |obj| + [obj.send(:id), nazrin_eval_field_data(obj)] + end + when :delete + hash[:delete] = objects.map do |obj| + obj.send(:id) + end + else + raise( + InvalidBatchOperationError, + "`#{type}` is not a valid batch operation" + ) + end + end + + nazrin_doc_client.batch(operations) end def nazrin_fields(fields) field_data = class_variable_get(:@@nazrin_search_field_data) fields.each do |field|