Skip to content

Support nested usage of JsonApiClient::Resource.with_headers#418

Open
tom-lord wants to merge 2 commits into
JsonApiClient:masterfrom
tom-lord:allow_nested_with_headers
Open

Support nested usage of JsonApiClient::Resource.with_headers#418
tom-lord wants to merge 2 commits into
JsonApiClient:masterfrom
tom-lord:allow_nested_with_headers

Conversation

@tom-lord

@tom-lord tom-lord commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

The problem:

When the .with_headers block closes, it wipes any headers that have been set. This can lead to counterintuitive issues in code; consider:

def my_record
  JsonApiClient::Resource.with_headers("Authorization: ...") do
    # fetch data
  end
end

def update_record
  JsonApiClient::Resource.with_headers("Authorization: ...") do
    my_record.save
  end
end

Regardless of whether the headers inside both blocks are the same or different, the JsonApiClient "forgets" them, halfway through the block! This causes my_record.save to fail as an unauthorised request.

The current workaround might be to instead do:

def my_record
  JsonApiClient::Resource.with_headers("Authorization: ...") do
    # fetch data
  end
end

def update_record
  record = my_record
  JsonApiClient::Resource.with_headers("Authorization: ...") do
    record.save
  end
end

...But this is confusing, and cumbersome.

My proposal in this PR is to "reset" the headers to their previous state at the end of a .with_headers block, rather than wiping them completely. So the first code block above will work as expected.

@tom-lord
tom-lord force-pushed the allow_nested_with_headers branch 2 times, most recently from 8b056e8 to 7adfaf0 Compare July 20, 2026 15:35
@tom-lord
tom-lord marked this pull request as ready for review July 20, 2026 15:35
@tom-lord
tom-lord force-pushed the allow_nested_with_headers branch from 7adfaf0 to a5d7565 Compare July 20, 2026 15:39
@tom-lord

Copy link
Copy Markdown
Contributor Author

CC: @gaorlov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant