Best Practices
Last updated
class PostsController < ApplicationController
def index
service = Post::FindAll.run(current_user:, current_organization:)
render json: service.posts
end
def create
service = Post::Create.run(attributes: params[:post], current_user:, current_organization:)
if service.success?
render json: service.post
else
render json: { errors: service.errors }, status: :unprocessable_entity
end
end
def unpublish
service = Post::Unpublish.run(id: params[:id], current_user:, current_organization:)
if service.success?
render json: service.post
else
render json: { errors: service.errors }, status: :unprocessable_entity
end
end
# ...
endclass ApplicationController < ActionController::API
private
def service_args(hash = {})
hash.reverse_merge(
current_user:,
current_organization:,
)
end
endclass PostsController < ApplicationController
def index
service = Post::FindAll.run(service_args)
render json: service.posts
end
def create
service = Post::Create.run(service_args(attributes: params[:post]))
if service.success?
render json: service.post
else
render json: { errors: service.errors }, status: :unprocessable_entity
end
end
def unpublish
service = Post::Unpublish.run(service_args(id: params[:id]))
if service.success?
render json: service.post
else
render json: { errors: service.errors }, status: :unprocessable_entity
end
end
# ...
end# app/services/concerns/authorize_user.rb
module AuthorizeUser
extend ActiveSupport::Concern
included do
# ...
end
end# app/services/application_service.rb
class ApplicationService < Operandi::Base
include AuthorizeUser
end