Skip to content

Instantly share code, notes, and snippets.

@mbuffa
Created October 10, 2016 19:03
Show Gist options
  • Save mbuffa/4203d9e8f734635d18819a9fd701fc37 to your computer and use it in GitHub Desktop.
Save mbuffa/4203d9e8f734635d18819a9fd701fc37 to your computer and use it in GitHub Desktop.
Rails Controller / Serializer / Service
class Controller
def create
outcome = Services::SomeCreation.new(params).call
return render_json Serializers::SomeSerializer(outcome, DEFAULT_STATUS_CODE).to_h
end
end
module Services
class SomeCreation
def initialize(params)
@params = params
end
def call
# Do fuzzy business logic here.
instance = SomeModel.new(@params)
(instance.save) ? instance : false
end
end
end
module Serializers
class SomeSerializer(item)
@item = item
@body = Jbuilder.new
build
end
def to_h
return error_hash if item == false
success_hash
end
private
def error_hash
{ body: {}, status: ERROR_CODE }
end
def success_hash
{ body: @body, status: (@item.new_record?) ? 201 : 200 }
end
def build
@body.data do |data|
data.id @item.id
end
@body.meta {}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment