Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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