Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set all of your Sinatra responses to be JSON?

Tags:

json

sinatra

I've been able to set all of my content types to be JSON in a before block, but is there a sinatra after filter that allows me to run to_json on all of the responses (instead of writing to_json 3 times in my example below)?

require 'sinatra'
require 'json'

before do
  content_type :json
end

get '/' do
  { song: "Hello" }.to_json
end

get '/go' do
  { song: "Go Yo Ho" }.to_json
end

get '/hi' do
  { song: "Wake me Up" }.to_json
end

Thanks!

like image 394
perseverance Avatar asked Dec 12 '22 02:12

perseverance


1 Answers

You can do that in an after block:

before do
  content_type :json
end

get '/' do
  { a: 1 }
end

after do
  response.body = JSON.dump(response.body)
end

Sinatra will re-calculate the correct content length for the updated body value.

An alternate way would be to use a helper:

helper do
  def j(data)
    JSON.dump(data)
  end
end

get '/' do
  j({ a: 1 })
end

The Sinatra::JSON project does the same thing. Also, you might want to look at libraries designed for building APIs like Grape or Goliath. These two libraries provide a easy way to attach decoders and encoders to handle this type of automatic conversion.

like image 91
Kashyap Avatar answered Feb 02 '23 04:02

Kashyap