Skip to content

Commit 9b0e0d0

Browse files
AaronRustadkarmi
authored andcommitted
[MODEL] Allow passing an ActiveRecord scope to the import method
Article.import scope: 'published' Related: elastic#104
1 parent fe16964 commit 9b0e0d0

File tree

3 files changed

+27
-4
lines changed

3 files changed

+27
-4
lines changed

elasticsearch-model/lib/elasticsearch/model/adapters/active_record.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,11 @@ module Importing
8383
# @see http://api.rubyonrails.org/classes/ActiveRecord/Batches.html ActiveRecord::Batches.find_in_batches
8484
#
8585
def __find_in_batches(options={}, &block)
86-
find_in_batches(options) do |batch|
86+
named_scope = options.delete(:scope)
87+
88+
scope = named_scope ? self.send(named_scope) : self
89+
90+
scope.find_in_batches(options) do |batch|
8791
batch_for_bulk = batch.map { |a| { index: { _id: a.id, data: a.__elasticsearch__.as_indexed_json } } }
8892
yield batch_for_bulk
8993
end

elasticsearch-model/lib/elasticsearch/model/importing.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,10 @@ module ClassMethods
6464
#
6565
# Article.import index: 'my-new-index', type: 'my-other-type'
6666
#
67+
# @example Pass an ActiveRecord scope to limit the imported records
68+
#
69+
# Article.import scope: 'published'
70+
#
6771
def import(options={}, &block)
6872
errors = 0
6973
refresh = options.delete(:refresh) || false

elasticsearch-model/test/unit/adapter_active_record_test.rb

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,13 +82,28 @@ def ids
8282
end
8383

8484
context "Importing" do
85+
setup do
86+
DummyClassForActiveRecord.__send__ :extend, Elasticsearch::Model::Adapter::ActiveRecord::Importing
87+
end
88+
89+
should "raise an exception when passing an invalid scope" do
90+
assert_raise NoMethodError do
91+
DummyClassForActiveRecord.__find_in_batches(scope: :not_found_method) do; end
92+
end
93+
end
94+
8595
should "implement the __find_in_batches method" do
8696
DummyClassForActiveRecord.expects(:find_in_batches).returns([])
87-
88-
DummyClassForActiveRecord.__send__ :extend, Elasticsearch::Model::Adapter::ActiveRecord::Importing
8997
DummyClassForActiveRecord.__find_in_batches do; end
9098
end
91-
end
9299

100+
should "limit the relation to a specific scope" do
101+
DummyClassForActiveRecord.expects(:find_in_batches).returns([])
102+
DummyClassForActiveRecord.expects(:published).returns(DummyClassForActiveRecord)
103+
104+
DummyClassForActiveRecord.__find_in_batches(scope: :published) do; end
105+
end
106+
107+
end
93108
end
94109
end

0 commit comments

Comments
 (0)