# Restful authentication refactoring

**URL:** <https://www.ruby-forum.com/t/restful-authentication-refactoring/156492>\
**Category:** Rails\
**Created:** [December 29, 2008, 12:15am UTC](https://www.ruby-forum.com/t/restful-authentication-refactoring/156492 "2008-12-29T00:15:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nicholas\_W](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f17d59/32.png) [@Nicholas\_W](https://www.ruby-forum.com/u/Nicholas_W)\
**Post date:** [December 29, 2008, 12:15am UTC](https://www.ruby-forum.com/t/restful-authentication-refactoring/156492/1 "2008-12-29T00:15:07Z")

</div>

Hi guys, this is more an RFC then a request for help …  
this is the code generated by restful authentication:

def create  
logout\_keeping\_session!  
@user = User.new(params[:user])  
@user.register! if @user && @user.valid?  
success = @user && @user.valid?  
if success && @user.errors.empty?  
redirect\_back\_or\_default(’/’)  
flash[:notice] = “blabla”  
else  
flash[:error] = “blabla”  
render :action =\> ‘new’  
end  
end

It seems incredibly redundant to me …  
This is how I refactored:

def create  
logout\_keeping\_session!  
@user = User.new( params[:user] )  
if @user && @user.valid?  
@user.register!  
redirect\_back\_or\_default( ‘/’ )  
flash[:notice] = “blabla”  
else  
flash[:error] = “blabla”  
render :action =\> ‘new’  
end  
end

I can’t understand why it checks 3 times if the object is valid, and  
even less that weird “state” variable it sets.  
I don’t see where it saves, but from my understanding of AASM the  
object is saved when the state change happens, probably using  
register! is a good idea.  
Maybe technoweenie is reading and can enlight me about the code  
duplication, if it’s really needed, and people with more experience  
with restful\_authentication can give me a suggestion.  
I imported specs and all tests pass, so everything should be fine.

TIA,  
ngw

---

<div class="post-metadata">

**Author:** ![Nicholas\_W](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f17d59/32.png) [@Nicholas\_W](https://www.ruby-forum.com/u/Nicholas_W)\
**Post date:** [December 29, 2008, 11:02am UTC](https://www.ruby-forum.com/t/restful-authentication-refactoring/156492/2 "2008-12-29T11:02:41Z")

</div>

I also noticed that “strange” redundancy, and refactored it the same way  
you did.
