From a088cf14d7ad624b83ece1bfd011b5feacadff61 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 8 Feb 2019 15:06:09 -0600 Subject: [PATCH] Add Serialize With fast_jsonapi In A Rails App as a rails til --- README.md | 3 +- ...ialize-with-fast-jsonapi-in-a-rails-app.md | 52 +++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 rails/serialize-with-fast-jsonapi-in-a-rails-app.md diff --git a/README.md b/README.md index 7c4c40b..ceef6b4 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_761 TILs and counting..._ +_762 TILs and counting..._ --- @@ -485,6 +485,7 @@ _761 TILs and counting..._ - [Secure Passwords With Rails And Bcrypt](rails/secure-passwords-with-rails-and-bcrypt.md) - [Select A Select By Selector](rails/select-a-select-by-selector.md) - [Select Value For SQL Counts](rails/select-value-for-sql-counts.md) +- [Serialize With fast_jsonapi In A Rails App](rails/serialize-with-fast-jsonapi-in-a-rails-app.md) - [Set Schema Search Path](rails/set-schema-search-path.md) - [Show Pending Migrations](rails/show-pending-migrations.md) - [Show Rails Models With Pry](rails/show-rails-models-with-pry.md) diff --git a/rails/serialize-with-fast-jsonapi-in-a-rails-app.md b/rails/serialize-with-fast-jsonapi-in-a-rails-app.md new file mode 100644 index 0000000..0e8ccfa --- /dev/null +++ b/rails/serialize-with-fast-jsonapi-in-a-rails-app.md @@ -0,0 +1,52 @@ +# Serialize With fast_jsonapi In A Rails App + +Netflix put out a Ruby gem for super fast JSON serialization -- +[`fast_jsonapi`](https://github.com/Netflix/fast_jsonapi). It is great for +serializing JSON responses for Rails API endpoints. + +First, add `gem 'fast_jsonapi'` to your `Gemfile` and `bundle install`. + +Then create the `app/serializers` directory for housing all of your JSON +serializers. + +Next you can create a `serializer` that corresponds to the model you want to +serialize: + +```ruby +# app/serializers/recipe_serializer.rb +class RecipeSerializer + include FastJsonapi::ObjectSerializer + + set_id :id + attributes :name, :source_url +end +``` + +Last, use it to generate a JSON response in your controller: + +```ruby +# app/controllers/recipes_controller.rb +class RecipesController < ApiController + def index + render json: RecipeSerializer.new(@current_user.recipes) + end +end +``` + +Requests to that endpoint will receive a response that looks something like +this: + +```json +{ + data: [ + { + id: 1, + attributes: { name: "Old Fashioned", source_url: "http://..." }, + }, + { + id: 2, + attributes: { name: "Sazerac", source_url: "http://..." }, + }, + ] +} +```