Module: Sinatra::RestAPI::Helpers

Defined in:
lib/sinatra/restapi.rb

Overview

Helper methods

There are some helper methods that are used internally be RestAPI, but you can use them too if you need them.

Instance Method Summary collapse

Instance Method Details

#rest_convert_to_json(obj) ⇒ Object



284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/sinatra/restapi.rb', line 284

def rest_convert_to_json(obj)
  # Convert to JSON. This will almost always work as the JSON lib adds
  # #to_json to everything.
  json = obj.to_json

  # The default to_json of objects is to JSONify the #to_s of an object,
  # which defaults to #inspect. We don't want that.
  return json  unless json[0..2] == '"#<'

  # Let's hope they redefined to_hash.
  return obj.to_hash.to_json  if obj.respond_to?(:to_hash)

  raise "Can't convert object to JSON. Consider implementing #to_hash to #{obj.class.name}."
end

#rest_paramsObject

rest_params

Returns the object from the request.

If the client sent application/json (or text/json) as the content type, it tries to parse the request body as JSON.

If the client sent a standard URL-encoded POST with a model key (happens when Backbone uses Backbone.emulateJSON = true), it tries to parse its value as JSON.

Otherwise, the params will be returned as is.



271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/sinatra/restapi.rb', line 271

def rest_params
  if File.fnmatch('*/json', request.content_type)
    JSON.parse request.body.read

  elsif params['model']
    # Account for Backbone.emulateJSON.
    JSON.parse params['model']

  else
    params
  end
end

#rest_respond(obj) ⇒ Object

rest_respond(object)

Responds with a request with the given object.

This will convert that object to either JSON or XML as needed, depending on the client's preferred type (dictated by the HTTP Accepts header).



248
249
250
251
252
253
254
255
256
257
# File 'lib/sinatra/restapi.rb', line 248

def rest_respond(obj)
  case request.preferred_type('*/json', '*/xml')
  when '*/json'
    content_type :json
    rest_convert_to_json obj

  else
    pass
  end
end