Skip to content

Instantly share code, notes, and snippets.

@adhrinae
Last active December 5, 2016 06:19
Show Gist options
  • Save adhrinae/9d2adf1a5d475ca675db35d2869c68c6 to your computer and use it in GitHub Desktop.
Save adhrinae/9d2adf1a5d475ca675db35d2869c68c6 to your computer and use it in GitHub Desktop.
Hanami with roar - Nested JSON API implement
class Book < Hanami::Entity
def author
AuthorRepository.new.find_with_book(self)
end
def comments
CommentRepository.new.find_with_book(self)
end
end
require 'roar/decorator'
require 'roar/json'
require_relative 'comment_representer' # required
module Api::Representers
class BookRepresenter < Roar::Decorator
include Roar::JSON
property :id
property :title
property :author, extend: Author , class: Author
property :description
collection :comments, extend: CommentRepresenter , class: Comment
end
end
class CommentRepository < Hanami::Repository
def find_with_book(book)
comments.where(book_id: book.id)
end
end
module Api::Controllers::Books
class Index
include Api::Action
expose :books
def call(params)
repo = BookRepository.new
books = repo.all
hashes = books.map do |book|
Api::Representers::Book.new(book).to_hash
end
self.status = 200
self.body = { books: hashes }.to_json
end
end
end
Hanami::Model.migration do
change do
create_table :books do
primary_key :id
foreign_key :author_id, :authors
column :title, String
column :description, String
column :created_at, DateTime
column :updated_at, DateTime
end
create_table :comments do
primary_key :id
foreign_key :book_id, :books
column :body, String
column :created_at, DateTime
column :updated_at, DateTime
end
create_table :authors do
primary_key :id
column :name, String
column :created_at, DateTime
column :updated_at, DateTime
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment