activeresource: Changing headers on base class doesn't change them in subclasses
Given models like:
ApiModel < ActiveResource::Base
self.site = "http://api.some-site.com"
end
Project < ApiModel
belongs_to :cluster
end
Cluster < ApiModel
has_many :projects
end
I want to be able to set authentication headers per request, to use OAuth for authentication. I thought this was possible (it was working, until I logged in with two different users) by just updating the headers:
before_action do
ApiModel.headers['Authorization'] = "Bearer #{...request.something...}"
end
But in the case of headers, calling the reader on a subclass sets the headers permanently for that subclass. This, to me, seems unintuitive given the fact that all connection options are inherited from the base class to begin with. It seems that I should be able to change them on the base class, and they should be used in all subclasses where they haven’t been explicitly overridden.
Is there a recommended way to update headers on all the objects that inherit from ActiveResource::Base without cycling through and updating every one? Would you be against changing the headers reader to avoid setting _headers on the subclass, and just return the merged headers (superclass.headers.merge(headers_state)) every time so that if a header is changed on the superclass, it will be always be returned when calling .headers on a subclass unless explicitly overridden?
This would be more analogous to how site and proxy are handled, from what I can tell. There is no merging happening in those cases, but the important part is that the attribute is never set in the readers, so if it is changed on the superclass, that change is reflected in the subclasses that haven’t overridden a given attribute.
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 1
- Comments: 16 (9 by maintainers)
Just refreshing this thread as my PR got marked as stale.
This is quite a serious issue, as shown by the following example:
If we consider this simple model:
Now the API handles two requests, on the same thread, for two users, with different credentials:
No!
Agreed that copy-on-read headers are surprising.
Here’s an approach that adds native bearer token support to ActiveResource::Connection itself: