Created
March 19, 2018 19:38
-
-
Save arempe93/d5e28b15da8712a618adf9672a1b62fb to your computer and use it in GitHub Desktop.
Grape route metaprogramming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module API | |
module Client | |
class Comments < Grape::API | |
[Post, Profile, Story].each do |model| | |
namespace model.table_name do | |
route_param :ref, type: String do | |
namespace :comments do | |
desc "List comments for #{model.name.downcase}" | |
params do | |
optional :per_page, type: Integer, default: 10 | |
optional :page, type: Integer, default: 1 | |
end | |
get do | |
commentable = find(model, ref: params[:ref]) | |
present :comments, paginate(commentable.comments) | |
end | |
desc "Create comment in #{model.name.downcase}" | |
params do | |
requires :body, type: String | |
end | |
post do | |
commentable = find(model, ref: params[:ref]) | |
comment = commentable.comments.create!(author_id: params[:_user_id], body: params[:body]) | |
MentionProcessingWorker.perform_async(comment.id, comment.base_class_name, :body) | |
present :comment, comment | |
end | |
end | |
end | |
end | |
end | |
namespace :comments do | |
route_param :id, type: Integer do | |
desc 'Edit comment' | |
params do | |
requires :body, type: String | |
end | |
put do | |
comment = find(Comment, id: params[:id]) | |
forbidden! unless comment.author_id == params[:_user_id] | |
comment.update!(body: params[:body], edited: true) | |
MentionProcessingWorker.perform_async(comment.id, comment.base_class_name, :body) | |
present :comment, comment | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment