#10
Mar 26, 2007

Refactoring User Name Part 1

Learn how to clean up your code through refactoring. This episode will show you how to move code from the view into the model to remove duplication and simplify the view.
Tags: refactoring
Download (11.8 MB, 5:44)
alternative download for iPod & Apple TV (7.8 MB, 5:44)
<!-- show.rhtml -->
Name: <%= @user.full_name %>
# models/user.rb
def full_name
  name = first_name + " "
  name += "#{middle_initial}. " unless middle_initial.nil?
  name += last_name
  name
end

RSS Feed for Episode Comments -10 comments

1. louis Jul 10, 2007 at 23:50

i was curious about the interpolation of middle_name in the full_name method. why use interpolation there if 'middle_initial' (which i assume is a column in the db) would work too? is it b/c <pre>middle_initial + " " unless middle_initial.nil?</pre> wouldn't work? or would it?
this site is amazing, btw!


2. Ryan Bates Jul 11, 2007 at 07:32

Concatonating strings like that will cause an error if middle_initial returns nil, which is why I chose to use string interpolation.


3. louis Jul 11, 2007 at 10:16

thanks!


4. Beck Lin Apr 30, 2008 at 08:47

Hi Ryan, I think
name += middle_initial + ". " unless middle_initial.nil?
still work, won't cause any error even if middle_initial returns nil.
B/c the priority should be:
(name += middle_initial + ". ") unless middle_initial.nil?
Please let me know if I'm wrong.


5. Venyamin Nov 28, 2009 at 14:03

Very very nice idea!!! Thanks for this post


6. buy propecia uk Apr 27, 2010 at 08:12

read some ppt on slideshar


7. Neodymium Magnets Jul 05, 2010 at 23:14

I think this is very dangerous


8. asics shose Jul 28, 2010 at 00:09

Hi Ryan, I think
name += middle_initial + ". " unless middle_initial.nil?
still work, won't cause any error even if middle_initial returns nil.
B/c the priority should be:
(name += middle_initial + ". ") unless middle_initial.nil?
Please let me know if I'm wrong.


9. free directory list Aug 11, 2010 at 22:15

good idea,i like it


10. uggs online Aug 13, 2010 at 22:14

Article is very nicely written.


11. mbt sport Aug 14, 2010 at 18:39

I just want to say the spirit is positive,but the content is simply.


12. mbt shoes sale Aug 14, 2010 at 18:40

It is a nice article,i appreciate it,i will keep it on my dashboad.


13. snow boots Aug 31, 2010 at 02:10

why I chose to use string interpolation.


14. Dolce & Gabbana Belts Sep 01, 2010 at 22:54

I think this is a great post. One thing that I find the most helpful is number five. Sometimes when I write, I just let the flow of the words and information come out so much that I loose the purpose. It’s only after editing when I realize what I’ve done. There’s defiantly a lot of great tips here I’m going to try to be more aware of.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source