Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/json_api_client/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,11 @@ def create!(attributes = {})
# @param headers [Hash] The headers to send along
# @param block [Block] The block where headers will be set for
def with_headers(headers)
previous_headers = self._custom_headers || {}
self._custom_headers = headers
yield
ensure
self._custom_headers = {}
self._custom_headers = previous_headers
end

# The current custom headers to send with any request made by this
Expand Down
33 changes: 33 additions & 0 deletions test/unit/custom_header_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,39 @@ def test_can_set_custom_headers
end
end

def test_can_nest_with_headers
stub_request(:get, "http://example.com/custom_header_resources/1")
.with(headers: {"X-My-Header" => "nested_value"})
.to_return(headers: {content_type: "application/vnd.api+json"}, body: {
data: {
type: "custom_header_resources",
id: "1",
attributes: {
title: "Rails is Omakase"
}
}
}.to_json)

stub_request(:get, "http://example.com/custom_header_resources/2")
.with(headers: {"X-My-Header" => "first_value"})
.to_return(headers: {content_type: "application/vnd.api+json"}, body: {
data: {
type: "custom_header_resources",
id: "2",
attributes: {
title: "Hello World"
}
}
}.to_json)

CustomHeaderResource.with_headers(x_my_header: "first_value") do
CustomHeaderResource.with_headers(x_my_header: "nested_value") do
CustomHeaderResource.find(1)
end
CustomHeaderResource.find(2)
end
end

def test_can_set_custom_accept_headers
stub_request(:get, "http://example.com/custom_header_resources/1")
.with(headers: {"Accept" => "application/vnd.api+json,application/vnd.api+json;version=2"})
Expand Down
Loading