setting headers in active resource request
Asked Answered
J

2

7

I have an Active Resource model that needs to set a header before posting/putting through save and update_attributes. The issue is that the header value needs to be different for each user, so it can't be set at the model level. I've seen examples for setting headers as part of a find, get, or custom methods, but no way to add it to a @myclass.save. Something like prefix_options but for headers would be ideal (@myclass.prefix_options[:myvar] = 'abcd') but I haven't found anything like that. Any insight would be appreciated.

Janniejanos answered 12/12, 2012 at 23:57 Comment(0)
Y
6

I just had a similar problem and overrode .headers on my ActiveResource class. ActiveResource::Base.headers is just a hash by default, but you can override it to be a method! <3 U Ruby.

http://rmosolgo.github.io/blog/2014/02/05/dynamically-generated-headers-for-activeresource-requests/

Yoke answered 8/2, 2014 at 17:16 Comment(2)
This does work as described for setting headers based on some constant data, but doesn't allow you to get something out of the current request right? (i.e. request.host or session variables) - Which may not be what the OP wanted, but just wanted to clarify the scope of the solution, because I'm looking for a way to do the latter.Senator
Can you paste the gist of your link here? Just in case the URL does not work in the future.Eustashe
W
2

I just checked in the code for 3.2.8, and it looks like it's not supported. I also don't see much opportunity for monkeypatching it.

https://github.com/rails/rails/blob/c2193c11ad215d3a2d7d35960630b3e1902a5082/activeresource/lib/active_resource/base.rb#L1359

It woud be a great patch to submit though, especially now that activeresource has been split off into its own gem for 4.0.

update

actually you can specify headers with a raw post request. you just can't specify them with the more abstract methods like create:

https://github.com/rails/rails/blob/c2193c11ad215d3a2d7d35960630b3e1902a5082/activeresource/lib/active_resource/connection.rb#L97

Wehner answered 13/12, 2012 at 1:5 Comment(1)
Thanks for your reply John. That's kind of what I was already thinking, so as a workaround I've written a class that extends aRes, and overrides save and update_attributes. My model will then extend that class. Far from ideal, but seems to work. Maybe I'll submit that as a patch to aRes unless it's there by design. I'm leaving this open for a while just in case someone knows of an alternativeJanniejanos

© 2022 - 2024 — McMap. All rights reserved.