Creating simple display methods

Lets say you have a User class with your basic fields including prefix, first name, last name, and middle initial. None of these are required fields, though you want to display them a lot in your templates. You find yourself doing this alot:

<%= @user.prefix %> <%= @user.first_name %> <%= @user.middle_initial %> <%= @user.last_name %>

Why? When methods and attributes are indistiguishable. Just add a little diddy to your User class.

def display_name
  display = ""
  [:prefix,:first_name,:middle_initial,:last_name].each do |name|
    display << send(name) << " " unless send(name).nil?
  end
  display.strip
end

Isn't this prettier?

<%= @user.display_name %>

2 Responses to “Creating simple display methods”

Another way to implement the method:

def display_name
[prefix, first_name, middle_initial, last_name].compact.join(‘ ‘)
end

The method #compact removes nils from the array. This should perform better, by not using #send (twice per field in most cases).

saniDraireJaw Says: #

Hey Everbody

I just became a member of this forum

Great job forum crew!

Just recently I read that there is a treatment for diabetes on http://www.healthcaredaily.org
Can diabetes seriously be cured? The source looks like a reliable healthcare news website

Has anyone tried beating diabetes this way?

Thanks a lot

saniDraireJaw

About

QuirkeyBlog is Aaron Quint's perspective on the ongoing adventure of Code, Life, Work and the Web.

twitter/@aq.

instagram/@quirkey.

github/quirkey.

QuirkeyBlog is proudly powered by WordPress

Categories