Skip to content

Commit 3b65a87

Browse files
authored
Add overridable jsonapi_context (#83)
This allows developers to set "context" as whatever they'd like
1 parent 9ee1bcc commit 3b65a87

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

lib/jsonapi_compliable/base.rb

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,11 +130,31 @@ def query_hash
130130
# @api private
131131
# @yieldreturn Code to run within the current context
132132
def wrap_context
133-
jsonapi_resource.with_context(self, action_name.to_sym) do
133+
jsonapi_resource.with_context(jsonapi_context, action_name.to_sym) do
134134
yield
135135
end
136136
end
137137

138+
# Override if you'd like the "context" to be something other than
139+
# an instance of this class.
140+
# In Rails, context is the controller instance.
141+
#
142+
# @example Overriding
143+
# # within your controller
144+
# def jsonapi_context
145+
# current_user
146+
# end
147+
#
148+
# # within a resource
149+
# default_filter :by_user do |scope, context|
150+
# scope.where(user_id: context.id)
151+
# end
152+
#
153+
# @return the context object you'd like
154+
def jsonapi_context
155+
self
156+
end
157+
138158
# Use when direct, low-level access to the scope is required.
139159
#
140160
# @example Show Action

spec/jsonapi_compliable_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,21 @@ def config(obj)
8484
end
8585
end
8686

87+
describe '#jsonapi_context' do
88+
let(:ctx) { double('context') }
89+
90+
before do
91+
allow(instance).to receive(:jsonapi_context) { ctx }
92+
allow(instance).to receive(:action_name) { 'index' }
93+
end
94+
95+
it 'sets the context to the given override' do
96+
instance.wrap_context do
97+
expect(instance.jsonapi_resource.context).to eq(ctx)
98+
end
99+
end
100+
end
101+
87102
describe '#render_jsonapi' do
88103
before do
89104
allow(instance).to receive(:force_includes?) { false }

0 commit comments

Comments
 (0)