Skip to content

Commit cad2f9f

Browse files
authored
Merge pull request #74 from code4lib/ar_with_scope
Doc ability to use scope/AR::Relation with ActiveRecordWrapper
2 parents f95f80c + b1705d3 commit cad2f9f

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

lib/oai/provider.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,21 @@
213213
# end
214214
# end
215215
# ```
216+
# ### Scopes for restrictions or eager-loading
217+
#
218+
# Instead of passing in a Model class to OAI::Provider::ActiveRecordWrapper, you can actually
219+
# pass in any scope (or ActiveRecord::Relation). This means you can use it for restrictions:
220+
#
221+
# OAI::Provider::ActiveRecordWrapper.new(Post.where(published: true))
222+
#
223+
# Or eager-loading an association you will need to create serialization, to avoid n+1 query
224+
# performance problems:
225+
#
226+
# OAI::Provider::ActiveRecordWrapper.new(Post.includes(:categories))
227+
#
228+
# Or both of those in combination, or anything else that returns an ActiveRecord::Relation,
229+
# including using custom scopes, etc.
230+
#
216231
# ### Sets?
217232
#
218233
# There is some code written to support oai-pmh "sets" in the ActiveRecord::Wrapper, but

test/activerecord_provider/helpers/providers.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,15 @@ class ARProvider < OAI::Provider::Base
1212
source_model ActiveRecordWrapper.new(DCField)
1313
end
1414

15+
class ARProviderWithScope < OAI::Provider::Base
16+
DATE_LESS_THAN_RESTRICTION = Time.parse("2007-03-12 19:30:22 UTC")
17+
18+
repository_name 'ActiveRecord Based Provider'
19+
repository_url 'http://localhost'
20+
record_prefix 'oai:test'
21+
source_model ActiveRecordWrapper.new(DCField.where("date < ?", DATE_LESS_THAN_RESTRICTION).includes(:sets))
22+
end
23+
1524
class SimpleResumptionProvider < OAI::Provider::Base
1625
repository_name 'ActiveRecord Resumption Provider'
1726
repository_url 'http://localhost'

test/activerecord_provider/tc_ar_provider.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,18 @@ def test_list_records
2828
assert_equal 100, doc.elements['OAI-PMH/ListRecords'].to_a.size
2929
end
3030

31+
def test_list_records_scope
32+
@provider = ARProviderWithScope.new
33+
34+
doc = nil
35+
assert_nothing_raised do
36+
doc = REXML::Document.new(@provider.list_records(:metadata_prefix => 'oai_dc'))
37+
end
38+
39+
expected_count = DCField.where("date < ?", ARProviderWithScope::DATE_LESS_THAN_RESTRICTION).count
40+
assert_equal expected_count, doc.elements['OAI-PMH/ListRecords'].to_a.size
41+
end
42+
3143
def test_list_identifiers
3244
assert_nothing_raised { REXML::Document.new(@provider.list_identifiers) }
3345
doc = REXML::Document.new(@provider.list_identifiers)

0 commit comments

Comments
 (0)