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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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