Skip to content

Instantly share code, notes, and snippets.

@abhchand
Last active September 12, 2017 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhchand/883015f2e39639158ab7dd56b7030b55 to your computer and use it in GitHub Desktop.
Save abhchand/883015f2e39639158ab7dd56b7030b55 to your computer and use it in GitHub Desktop.
Blog Post: The interactor design pattern
class UsersController < ApplicationController
def create
# Validate the form data and return if it is not correct
# We'll come back and fill in the ???? with the call to the
# interactor shortly.
unless (????)
flash[:error] = ????
redirect_to(new_users_path)
return
end
user = User.create!(user_params)
flash[:success] = "Woohoo, you created an account"
redirect_to(user_path(@ser))
end
private
def user_params
@user_params || = params.require(:user).permit(
:first_name,
:last_name,
:email
)
end
end
class UsersController < ApplicationController
def create
validator = UsersCreateActionInteractor.call(params: user_params)
unless validator.success?
flash[:error] = validator.err_msg
redirect_to(new_users_path)
return
end
user = User.create!(user_params)
flash[:success] = "Woohoo, you created an account"
redirect_to(user_path(@ser))
end
private
def user_params
@user_params || = params.require(:user).permit(
:first_name,
:last_name,
:email
)
end
end
class UsersCreateActionInteractor
include Interactor
def call
@params = context.params
case
when name_is_blank? then handle_blank_name
when email_is_blank? then handle_blank_email
when email_is_taken? then handle_email_is_taken
when email_format_invalid? then handle_email_format_invalid
else
handle_success
end
end
private
def name_is_blank?
@params[:first_name].blank? || @params[:last_name].blank?
end
def handle_blank_name
# Note: The interactor gem supports a short-hand notation for
# the below actions:
# > context.fail!(err_msg: "...")
context.err_msg = "Please fill in a name"
context.fail!
end
def email_is_blank?
@params[:email].blank?
end
def handle_blank_email
context.err_msg = "Please fill in an email"
context.fail!
end
def email_is_taken?
User.find_by_email(@params[:email]).any?
end
def handle_email_is_taken
context.err_msg = "That email already exists!"
context.fail!
end
def email_format_invalid?
(@params[:email] =~ /.*@.*\..*/i).blank?
end
def handle_email_format_invalid
context.err_msg = "Sorry, that doesn't look like an email address"
context.fail!
end
def handle_success
# n/a
end
end
@abhchand
Copy link
Author

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