I have the following model:
# == Schema Information
#
# Table name: clients
#
# id :integer not null, primary key
# first_name :string(255)
# last_name :string(255)
# email :string(255)
#
class Client < ActiveRecord::Base
def full_name
if first_name.blank? && last_name.blank?
'Name: unknown'
else
first_name + ' ' + last_name
end
end
def email_address
email.blank? ? 'Email: unknown' : email
end
end
Which has the following spec:
RSpec.describe Client, type: :model do
describe 'full_name' do
it 'should return first_name + last_name if not blank' do
@client = create(:client, first_name: 'John', last_name: 'Doe')
@client.full_name.should == 'John Doe'
end
it "should return 'Name: unkonwn' if name is blank" do
@client = create(:client, first_name: '', last_name: '')
@client.full_name.should == 'Name: unknown'
end
end
describe 'email_address' do
it 'should return email if email is not blank' do
@client = create(:client, email: '[email protected]')
@client.email_address.should == '[email protected]'
end
it "should return 'Email: unkonwn' if email is blank" do
@client = create(:client, email: '')
@client.email_address.should == 'Email: unknown'
end
end
end
As you can see I am creating methods (email_address
, full_name
) to display attributes (or a combination of attributes) in views. If the attribute is blank I want to return a string saying the value is unknown.
I have many more attributes that I would like to display this way, but it seems inefficient to come up with alternative method names for methods that simply return the attribute or the "blank alternative".
As an example, these are some of the other attributes: sex, age, source. Rather than calling client.sex
or client.age
I would create a method and call client.name_of_sex
or client.age_string
-- it starts to get awkward (I went from email
to email_address
in the above example).
The alternative I know is to put logic in my views:
<% if client.email.blank? %>
Email: unknown
<% else %>
<%= client.email %>
<% end %>
This is inappropriate for a number of reasons, but my current alternative (the example above) doesn't seem to be optimal.
Is this a point where I should get into making a view-model? Is there some other way I could elegantly perform the actions I want? Or is the way I'm doing it a reasonable thing to do (I'm going to have a lot of attributes I want to display this way)?