Skip to content

Commit 2c2d3ea

Browse files
authored
Allow for per-action resources (#99)
Sometimes you want `index` powered by ElasticSearch but `show` is a normal ActiveRecord Resource. While we still support the existing syntax, you can now pass a hash of per-action Resources: ```ruby class PostsController < ApplicationController jsonapi resource: { index: PostSearchResource, show: PostResource } end ```
1 parent 82f9021 commit 2c2d3ea

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

lib/jsonapi_compliable/base.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,14 @@ def sideload_whitelist
106106
#
107107
# @return [Resource] the configured Resource for this controller
108108
def jsonapi_resource
109-
@jsonapi_resource ||= self.class._jsonapi_compliable.new
109+
@jsonapi_resource ||= begin
110+
resource = self.class._jsonapi_compliable
111+
if resource.is_a?(Hash)
112+
resource[action_name.to_sym].new
113+
else
114+
resource.new
115+
end
116+
end
110117
end
111118

112119
# Instantiates the relevant Query object

spec/integration/rails/finders_spec.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,11 @@ class AuthorResource < JsonapiCompliable::Resource
131131
def index
132132
render_jsonapi(Author.all)
133133
end
134+
135+
def show
136+
scope = jsonapi_scope(Author.all)
137+
render_jsonapi(scope.resolve.first, scope: false)
138+
end
134139
end
135140

136141
let!(:author1) { Author.create!(first_name: 'Stephen', dwelling: house, state: state, organization: org1) }
@@ -203,6 +208,33 @@ def json
203208
end
204209
end
205210

211+
context 'when action-specific resources' do
212+
before do
213+
klass = Class.new(JsonapiCompliable::Resource) do
214+
type :authors
215+
use_adapter JsonapiCompliable::Adapters::ActiveRecord
216+
end
217+
218+
controller.class.jsonapi resource: {
219+
index: Integration::AuthorResource,
220+
show: klass
221+
}
222+
end
223+
224+
it 'uses the correct resource for each action' do
225+
get :index, params: { include: 'books' }
226+
expect(json_includes('books').length).to eq(2)
227+
controller.instance_variable_set(:@jsonapi_resource, nil)
228+
expect {
229+
if Rails::VERSION::MAJOR >= 5
230+
get :show, params: { id: author1.id, include: 'books' }
231+
else
232+
get :show, id: author1.id, params: { include: 'books' }
233+
end
234+
}.to raise_error(JsonapiCompliable::Errors::InvalidInclude)
235+
end
236+
end
237+
206238
context 'sideloading has_many' do
207239
# TODO: may want to blow up here, only for index action
208240
it 'allows pagination of sideloaded resource' do

0 commit comments

Comments
 (0)