Josh Bavari's Thoughts

Thoughts on technology and philosophy

Using JSON Serializers in Sinatra

about a 1 minute read

I ran into a quick little issue with serializing some of my Sequel models.

The official JSON serializer docs are great, I just wanted to shine more light on the issue.

If you’re using Sequel models, just throw in the quick line of plugin :json_serializer.

1
2
3
4
5
6
7
8
# Get our database connection
require_relative "./db"
module ScoreboardApi
  class Team < Sequel::Model(:team)
    plugin :json_serializer
    serialize_attributes :json, :name
  end
end

Then, you just use the Sinatra contrib gem to have it json serializer attach:

1
2
3
4
# Web framework
gem "sinatra", "1.4.6", require: "sinatra/base"
# Sinatra addons - JSON, Namespace
gem "sinatra-contrib", "1.4.6"

Set up your API routes and spit out JSON:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
require "bundler"
require "sinatra/base"
require "sinatra/json"
require "sinatra/namespace"

require "./models/scoreboard"
require "./models/team"

Bundler.require

module ScoreboardApi
  class App < Sinatra::Application
    register Sinatra::Namespace
    configure do
      disable :method_override
      disable :static

      set :sessions,
          :httponly     => true,
          :secure       => production?,
          :expire_after => 31557600, # 1 year
          :secret       => ENV["SESSION_SECRET"]
    end

    use Rack::Deflater

    namespace "/api/v1" do
      get "/scores" do
        json :scoreboard => Scoreboard.all
      end

      get "/teams" do
        json :teams => Team.all
      end
    end
  end
end

That”s all folks!

Comments