Forum: Ruby on Rails Restful authentication refactoring

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Nicholas W. (Guest)
on 2008-12-29 01:15
(Received via mailing list)
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
Fernando P. (Guest)
on 2008-12-29 12:02
I also noticed that "strange" redundancy, and refactored it the same way
you did.
This topic is locked and can not be replied to.