Skip to content

Instantly share code, notes, and snippets.

@chrismccord
Last active January 8, 2017 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismccord/6298006 to your computer and use it in GitHub Desktop.
Save chrismccord/6298006 to your computer and use it in GitHub Desktop.
Rails callback/listener approach to shared service object behavior from controllers
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