Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting headers in active resource request

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.

like image 357
d-coded Avatar asked Dec 12 '12 23:12

d-coded


2 Answers

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/

like image 127
rmosolgo Avatar answered Oct 19 '22 01:10

rmosolgo


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

like image 29
John Bachir Avatar answered Oct 18 '22 23:10

John Bachir