In an application I am writing, we gather three items about a person's Name: Their Username and their First and last names.
In different parts of the application we want to have their names displayed in different ways. For Example, we want to have the opening page say Hi, First Name!. We want log entries to display their Username in one field, and their Last Name comma First Name in another field. We want to have their First Initial comma Last Name in another area.
In this application, we store names as attributes in an attributes table, rather then in the person table. I talked about Cross Model Attributes a while ago.
We assume the following:
- Person is the model for people
- Person.name is the username
- Attrib is the model for attributes
- Attrib.name holds the name of the Attribute
- Attrib.value holds the value
- We have polymorphic associations set up
To accommodate all of these different display needs, I wrote this little snippet of code:
def namer(person_id, format)
#Namer will return the person_id's name in the desired format
#0 is First name only
#1 is Last name only
#2 is Last Name, First Name
#3 is First name Last name
#4 First Inital, Last Name
#5 First name, last inital
person = Person.find_by_id(person_id)
unless person.attrib.find_by_name('First Name').nil?
f = person.attrib.find_by_name('First Name')
first = f[:value].to_s
else
tmp = 'No Name'
return person.name
end
unless person.attrib.find_by_name('Last Name').nil?
l = person.attrib.find_by_name('Last Name')
last = l[:value].to_s
else
tmp = 'No Name'
return person.name
end
case format
when 0 return first
when 1 return last
when 2 tmp = last + ', ' + first
return tmp
when 3 tmp = first + ' ' + last
return tmp
when 4 tmp = first[0..0].upcase + ' ' + last
return tmp
when 5 tmp = first + ' ' + last[0..0].upcase
return tmp
end
end