Skip to content

Instantly share code, notes, and snippets.

@cored
Last active December 23, 2015 07:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save cored/6599407 to your computer and use it in GitHub Desktop.
Save cored/6599407 to your computer and use it in GitHub Desktop.
class UsersController < ApplicationController
def create
@user = User.new params[:user]
return render 'new' unless @user.save
flash[:notice] = "The user was created succesfully"
redirect_to :index
end
end
class UsersController < ApplicationController
def create
CreateUser.new(User).call(
params[:user],
on_success: ->(user) do
flash[:notice] ="The user was created successfully"
redirect_to :index
end,
on_failure: ->(user) do
render 'new'
end
end
end
class CreateUser
def initialize(users_repository)
@users_repository = users_repository
end
def call(attributes: {}, on_success: nil, on_failure: nil)
user = @users_repository.new attributes
return on_faiulre[user] unless user.save
on_success[user]
end
end
@kchien
Copy link

kchien commented Sep 18, 2013

I like how you inject User into the CreateUser model, rather than using it directly in CreateUser#call. In the codebase I have at work, I might default the argument in the CreateUser constructor so that client code doesn't need to worry about the collaborators.

However, I can definitely see why you wouldn't want to do that, so that CreateUser isn't tightly coupled to User.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment