From d4b0b879a03e4111ae3ce0470bb788e6dba576d9 Mon Sep 17 00:00:00 2001 From: Andrew Tomaka Date: Mon, 12 Oct 2015 17:13:49 -0400 Subject: [PATCH] Simple serializer --- Gemfile | 1 + Gemfile.lock | 19 +++++++++++++++++++ app.rb | 9 +++++++-- serializers/joke_serializer.rb | 3 +++ 4 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 serializers/joke_serializer.rb diff --git a/Gemfile b/Gemfile index d01d958..073e9c9 100644 --- a/Gemfile +++ b/Gemfile @@ -5,6 +5,7 @@ gem 'activerecord' gem 'sinatra' gem 'sinatra-activerecord' +gem 'sinatra-active-model-serializers' group :production do gem 'pg' diff --git a/Gemfile.lock b/Gemfile.lock index b234b50..cd308fb 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,6 +1,8 @@ GEM remote: https://rubygems.org/ specs: + active_model_serializers (0.9.3) + activemodel (>= 3.2) activemodel (4.2.4) activesupport (= 4.2.4) builder (~> 3.1) @@ -15,6 +17,7 @@ GEM thread_safe (~> 0.3, >= 0.3.4) tzinfo (~> 1.1) arel (6.0.3) + backports (3.6.6) builder (3.2.2) ffi (1.9.10) i18n (0.7.0) @@ -23,10 +26,13 @@ GEM rb-fsevent (>= 0.9.3) rb-inotify (>= 0.9) minitest (5.8.1) + multi_json (1.11.2) pg (0.18.3) rack (1.6.4) rack-protection (1.5.3) rack + rack-test (0.6.3) + rack (>= 1.0) rb-fsevent (0.9.6) rb-inotify (0.9.5) ffi (>= 0.5.0) @@ -36,9 +42,21 @@ GEM rack (~> 1.4) rack-protection (~> 1.4) tilt (>= 1.3, < 3) + sinatra-active-model-serializers (0.2.1) + active_model_serializers (>= 0.9.0) + sinatra (~> 1.4) + sinatra-activerecord (>= 2.0.0) + sinatra-contrib (>= 1.4.1) sinatra-activerecord (2.0.9) activerecord (>= 3.2) sinatra (~> 1.0) + sinatra-contrib (1.4.6) + backports (>= 2.0) + multi_json + rack-protection + rack-test + sinatra (~> 1.4.0) + tilt (>= 1.3, < 3) sqlite3 (1.3.11) thread_safe (0.3.5) tilt (2.0.1) @@ -53,6 +71,7 @@ DEPENDENCIES pg rerun sinatra + sinatra-active-model-serializers sinatra-activerecord sqlite3 diff --git a/app.rb b/app.rb index afe2241..f16e034 100644 --- a/app.rb +++ b/app.rb @@ -1,11 +1,16 @@ require 'rubygems' require 'bundler' require 'bundler/setup' +require 'json' +require 'sinatra/json' Bundler.require require './config/environments' require './model/joke' +require './serializers/joke_serializer' + +register Sinatra::ActiveRecordExtension before do content_type :json @@ -13,7 +18,7 @@ before do end get '/jokes' do - Joke.all.to_json + json Joke.all, root: false end post '/jokes' do @@ -34,7 +39,7 @@ get '/jokes/:id' do return end - @joke.to_json + json @joke, root: false end put '/jokes/:id' do diff --git a/serializers/joke_serializer.rb b/serializers/joke_serializer.rb new file mode 100644 index 0000000..f462ea4 --- /dev/null +++ b/serializers/joke_serializer.rb @@ -0,0 +1,3 @@ +class JokeSerializer < ActiveModel::Serializer + attributes :joke, :punchline +end