Skip to content

Commit 3c2ba9b

Browse files
committed
Extract Resource#find's resource transformation
Most of the behaviour of JSONAPI::Resource#find can be controlled by reimplementing #records, #filter_record, #sort_record, etc. By moving the resource transformation into #resources_for, we've remove one of the final bits of logic out of the #find. All #find defines is the order of operations and in many cases can be left as is. My specific use case is to delegate a single class of models to different resources. The caching behaviour in #find's transformation prevents me from simply reimplementing Resource#resource_for.
1 parent 5e4fd81 commit 3c2ba9b

2 files changed

Lines changed: 9 additions & 0 deletions

File tree

lib/jsonapi/resource.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -636,6 +636,10 @@ def find(filters, options = {})
636636

637637
records = apply_pagination(records, options[:paginator], order_options)
638638

639+
resources_for(records, context)
640+
end
641+
642+
def resources_for(records, context)
639643
resources = []
640644
resource_classes = {}
641645
records.each do |model|

test/unit/resource/resource_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -611,4 +611,9 @@ def test_resource_performs_validations_in_custom_context
611611
end
612612
assert_equal(err.error_messages[:base], ['Record is invalid'])
613613
end
614+
615+
def test_resources_for_transforms_records_into_resources
616+
resources = PostResource.resources_for([Post.first], {})
617+
assert_equal(PostResource, resources.first.class)
618+
end
614619
end

0 commit comments

Comments
 (0)