Default params for POST in HTTParty by jgn on Wednesday, May 5, 2010 in Code

So I was looking at the API for ping.fm (http://groups.google.com/group/pingfm-developers/web/api-documentation?\_done=%2Fgroup%2Fpingfm-developers%3F), and thought: Ah, this would be easy to wrap with HTTParty (http://github.com/jnunemaker/httparty).

For ping.fm, all requests must be POSTs, and each request much include a couple of keys. But in HTTParty, you can't specify default params that should be used every time for POST.

So I fixed that. See below. I'm too lazy to fork, add my code, write tests, and create a pull request, so I'll just have it here for posterity.

Then I realized that there is probably a gem for ping.fm -- and there is! So I won't be using HTTParty after all!

But here's the code. For a Rails app, just put this in a file in config/initializers.

[code language='ruby'] # Provide means for HTTParty to allow for default body parameters module HTTParty module ClassMethods def default_body_params(h={}) raise ArgumentError, 'Default body params must be a hash' unless h.is_a?(Hash) default_options[:default_body_params] ||= {} default_options[:default_body_params].merge!(h) end end class Request def body if options[:default_body_params] if options[:body] if options[:body].is_a?(Hash) options[:body] = options[:default_body_params].merge(options[:body]) end else options[:body] = options[:default_body_params] end end # original: options[:body].is_a?(Hash) ? options[:body].to_params : options[:body] end end end

comments powered by Disqus