Created
October 10, 2016 19:03
-
-
Save mbuffa/4203d9e8f734635d18819a9fd701fc37 to your computer and use it in GitHub Desktop.
Rails Controller / Serializer / Service
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
class Controller | |
def create | |
outcome = Services::SomeCreation.new(params).call | |
return render_json Serializers::SomeSerializer(outcome, DEFAULT_STATUS_CODE).to_h | |
end | |
end |
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
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 |
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
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