Last active
January 8, 2017 21:47
-
-
Save chrismccord/6298006 to your computer and use it in GitHub Desktop.
Rails callback/listener approach to shared service object behavior from controllers
This file contains hidden or 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 CommentsController < ApplicationController | |
def create | |
CommentCreator.new(current_user, params[:comment], self).create | |
end | |
private | |
def create_successful(comment) | |
redirect_to comment_path(comment) | |
end | |
def create_failure(comment, errors) | |
@comment = comment | |
render :edit | |
end | |
end | |
class Api::CommentsController < ApplicationController | |
def create | |
CommentCreator.new(current_user, params[:comment], self).create | |
end | |
private | |
def create_successful(comment) | |
render json: comment | |
end | |
def create_failure(comment, errors) | |
render json: {errors: errors} | |
end | |
end | |
class CommentCreator | |
def initialize(user, comment_params, listener) | |
@comment = user.comments.new(comment_params) | |
@listener = listener | |
end | |
def create | |
if @comment.save | |
@listener.create_successful(@comment) | |
else | |
@listener.create_failure(@comment, @comment.errors.full_messages) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment