Back to Course

Practice · SOLID · SRP · Card 1

Spot the responsibilities in this controller action

The code below works, ships, and is normal-looking Rails. It's also doing four different jobs that should probably live elsewhere. Name them.

The code

A signup controller. What does this action actually do, end to end?

def create
  @user = User.new(user_params)
  @user.password = SecureRandom.hex(8) if user_params[:password].blank?

  if @user.save
    Stripe::Customer.create(email: @user.email, name: @user.name)
    WelcomeMailer.with(user: @user).welcome_email.deliver_later
    Rails.logger.info "signup: #{@user.id} from IP #{request.remote_ip}"
    redirect_to dashboard_path, notice: "Welcome!"
  else
    render :new, status: :unprocessable_entity
  end
end

The question

List the distinct responsibilities mixed into this action. Then think about where each one should live.

Take a moment. A controller's actual job is to read the request, call something to do the work, and render the response. Anything in this action that isn't one of those three is misplaced.