Jul 14, 2011
Evolution of a rails programmer

Idiomatic rails action for registering a user if he doesn't exist:

After a year of programming in lisp, I find it most natural to write:

Is this overly concise/obfuscated? I like it because it concisely expresses the error case as an early exit; most of the space is devoted to the successful save, which is straight-line code without distracting branches. It's clearer that we either pick an existing user or create a new one. Form follows function.

comments

      
  • Hrishi Mittal, 2011-07-16: I like your new style. It's much cleaner and easier to read, but are you sure it works properly and catches all errors?   
        
    • Kartik Agaram, 2011-07-16: Thanks. Yes I'm fairly sure the two versions are semantically identical.
      
  • Dave Doolin, 2011-08-26: Last year being new to Ruby I would have said "overly concise," even pretentiously succinct. This year (a year in) I'm ok with it. But really, next year and after are when it matters. Idioms come and go.  Good idioms (presumably) stand the test of time.  I would agree, in any case, that the original feels "clunky" in some vague manner.   
  • sshaw, 2011-10-26: If I blur my eyes and look at the 2nd form, I see Perl...   I think the 1st can be cleaned up a bit with:
    user = User.find_or_create_by_email(params[:user][:email], params[:user])
    
    and removing the else. 

Comments gratefully appreciated. Please send them to me by any method of your choice and I'll include them here.

archive
projects
writings
videos
subscribe
Mastodon
RSS (?)
twtxt (?)
Station (?)