Skip to content

Instantly share code, notes, and snippets.

@jaigouk
Last active August 29, 2015 14:08
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 jaigouk/d0dc609d5ff96b3ea651 to your computer and use it in GitHub Desktop.
Save jaigouk/d0dc609d5ff96b3ea651 to your computer and use it in GitHub Desktop.
skinny controller
#Let's extract some registration logic out of our controllers into a UserRegistration class.
#This class should take user_params as arguments to its constructor,
#which are used to initialize a new User (not create).
#This newly initialized user should be available as an attr_reader.
#You'll also want to move the valid_background_check? method
#into this new class as a private method, we'll use this later to finish creating the User.
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if valid_background_check?
@user.is_approved = true
end
if @user.save
redirect_to @user
else
render :new
end
end
private
def valid_background_check?
!!(@user.valid_ssn? || @user.valid_address?)
end
def user_params
params.require(:user).permit(:name, :email, :ssn, :address)
end
end
class UserRegistration
private
# private methods go here
end
class UsersController < ApplicationController
def create
registration = UserRegistration.new(user_params)
@user = registration.user
if registration.create
redirect_to @user
else
render :new
end
end
private
def user_params
params.require(:user).permit(:name, :email, :ssn, :address)
end
end
class UserRegistration
attr_reader :user
def initialize(params)
@user = User.new(params)
end
def create
if valid_background_check?
@user.is_approved = true
end
@user.save
end
private
# private methods go here
def valid_background_check?
!!(@user.valid_ssn? || @user.valid_address?)
end
end
@kibaekr
Copy link

kibaekr commented Nov 2, 2014

in line 5 of second file, how does "registration.user' know which user to find? is it just from the attr_reader?

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