Skip to content

Instantly share code, notes, and snippets.

@sergio-fry
Created January 31, 2018 11:02
Show Gist options
  • Save sergio-fry/eb5b6d609539ada9012f7dc991dab728 to your computer and use it in GitHub Desktop.
Save sergio-fry/eb5b6d609539ada9012f7dc991dab728 to your computer and use it in GitHub Desktop.
Ruby Rails JSON API example using ROAR JSON API
# gem 'roar-rails'
# gem 'roar-jsonapi'
class V2::BasePresenter
include ActiveModel::Validations
# Десериализация из JSON
# @return [V2::BasePresenter]
def self.from_json(json)
serializer.new(new).from_json json
end
# Сериализация в JSON
# @return [String]
def to_json
self.class.serializer.new(self).to_json
end
# Объявление нового аттрибута
# @param [String|Symbol] name название
def self.property(name)
@properties ||= []
@properties << name.to_sym
attr_accessor name
end
class << self
attr_reader :properties
# Возвращает анонимный класс декоратора
# @return [Class]
def serializer
klass = self
@serializer ||=
Class.new Roar::Decorator do
include Roar::JSON::JSONAPI.resource :ball
attributes do
klass.properties.each do |name|
property name
end
end
end
end
end
end
class V2::BallPresenter < V2::BasePresenter
property :id
property :brand
property :size
validates :brand, presence: true
end
# Базовый класс контроллеров V2 API.
class V2::BaseController < V1::BaseController
end
# Пример API V2 реализующий JSON API
class V2::PingController < V2::BaseController
respond_to :json
# возвращает мяч, тот же, что и получает
# GET /v2/ping
def ping
ball = V2::BallPresenter.from_json request.body.read
if ball.valid?
render json: ball.to_json
else
render json: { errors: ball.errors }, status: 400
end
end
private
def skip_requires
true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment