Skip to content

Instantly share code, notes, and snippets.

@belgoros
Last active November 19, 2019 16:28
Show Gist options
  • Save belgoros/127a7e45104c27791f90daef01fab6c8 to your computer and use it in GitHub Desktop.
Save belgoros/127a7e45104c27791f90daef01fab6c8 to your computer and use it in GitHub Desktop.
AMS for a non-AR model, Rails 5.2.3
# models/user.rb
class User
include ActiveModel::Model
attr_accessor :username, :first_name, :last_name, :id
end
#serializers/user_serializer.rb
class UserSerializer < ActiveModelSerializers::Model
attributes :id, :first_name, :last_name, :username
end
# controllers/users_controller.rb
class UsersController < ApplicationController
before_action :init_users
def index
render jsonapi: @users
end
def show
@user = @users.select {|u| u.id == params[:id].to_i}.first
if @user
render jsonapi: @user
else
render jsonapi: {message: "Wrong user ID"}, status: :not_found
end
end
private
def init_users
@users ||= []
if @users.empty?
(1...10).to_a.each do |x|
@users << User.new(
id: x,
username: "user-#{x}",
first_name: "FName-#{x}",
last_name: "LName-#{x}"
)
end
end
@users
end
end
# initializers/ams.rb
# frozen_string_literal: true
# In order to properly handle JSON API responses, we need to register a JSON API renderer,
# like so:
ActiveSupport.on_load(:action_controller) do
require 'active_model_serializers/register_jsonapi_renderer'
end
ActiveModelSerializers.config.adapter = :json_api
ActiveModelSerializers.config.key_transform = :unaltered
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment