This repository provides a Hobby extension for JSON requests and responses.
It tries to parse request.body as JSON.
If succeeded, it will store a parsed Ruby object in json.
If request.body happened not to have a valid JSON,
it will halt the request with 400 status code.
A response will be converted to JSON by calling .to_json on the latest action object.
Here is an echo service(it returns the same JSON posted by a request):
require 'hobby'
require 'hobby/json'
class Echo
include Hobby
include JSON
post { json }
endAnother example could be an adding service.
It expects to get an array of numbers in the numbers field, after which it sums them up,
and returns the result in the result field.
require 'hobby'
require 'hobby/json'
class Adder
include Hobby
include JSON
post do
{ result: json['numbers'].sum }
end
endYou can put this in config.ru:
run Adder.newand run it with rackup. Then, the service can be accessed like so:
➜ ~ curl -H "Content-Type: application/json" -X POST -d '{"numbers":[1,2,3]}' http://localhost:9292
{"result":6}%