Method: MLS#post

Defined in:
lib/mls.rb

#post(url, body = {}, *valid_response_codes, &block) ⇒ Object

Posts to url on the MLS Server. Automatically includes any headers returned by the MLS#headers function.

Paramaters
  • url - The url on the server to Post to. This url will automatically be prefixed with "/api". To post to "/api/accounts" pass "/accounts" as url

  • body - A Ruby object which is converted into JSON and added in the request Body.

  • valid_response_codes - An Array of HTTP response codes that should be considered accepable and not raise exceptions. For example If you don’t want a MLS::Exception::NotFound to be raised when a POST request returns a 404 pass in 404, and the response body will be returned if the status code is a 404 as it does if the status code is in the 200..299 rage. Status codes in the 200..299 range are always considred acceptable

Return Value

Returns the return value of the &block if given, otherwise the response object

Examples:

#!ruby
MLS.post('/example') # => #<Net::HTTP::Response>

MLS.post('/example', {:body => 'stuff'}) # => #<Net::HTTP::Response>

MLS.post('/404') # => raises MLS::Exception::NotFound

MLS.post('/404', nil, 404, 450..499) # => #<Net::HTTP::Response>

MLS.post('/404', nil, [404, 450..499]) # => #<Net::HTTP::Response>

MLS.post('/404', nil, 404) # => #<Net::HTTP::Response>

# this will still raise an exception if the response_code is not valid
# and the block will not be called
MLS.post('/act') do |response, response_code|
  # ...
end


260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/mls.rb', line 260

def post(url, body={}, *valid_response_codes, &block)
  body ||= {}
  
  req = Net::HTTP::Post.new("/api#{url}")
  req.body = Yajl::Encoder.encode(body)
  add_headers(req)
  
  response = connection.request(req)
  handle_response(response, valid_response_codes)

  if block_given?
    yield(response, response.code.to_i)
  else
    response
  end
end