patternrubyMinor
Presenting a time as a string
Viewed 0 times
presentingstringtime
Problem
I have three methods that are really similar but do slightly different things. This doesn't feel very DRY to me, but I can't think of a way to reduce the duplication. Here are the methods, I think they're fairly self explanatory:
Each method just presents a time as a string with certain options, and if the time object they're trying to present is nil, they return an empty string.
Any ideas how to DRY this up?
# Present a date as a string, optionally without a year
# Example output: "December 1, 2011"
def date_string(year=true)
if date
str = "%B %e"
str += ", %Y" if year
date.strftime(str).gsub(' ',' ')
else
""
end
end
# Present a time as a string, optionally with a meridian (am/pm)
# Example output: "1:30 PM"
def start_time_string(meridian=true)
if start_time
str = "%l:%M"
str += " %p" if meridian
start_time.strftime(str).lstrip
else
""
end
end
# Present a time as a string, optionally with a meridian (am/pm)
# Example Output: "2:00"
def end_time_string(meridian=true)
if end_time
str = "%l:%M"
str += " %p" if meridian
end_time.strftime(str).lstrip
else
""
end
endEach method just presents a time as a string with certain options, and if the time object they're trying to present is nil, they return an empty string.
Any ideas how to DRY this up?
Solution
Well, I don't see much you can do with the first method (being as it has a different responsibility than the other two). You can just combine the latter two methods into one and make the time object a parameter, like such:
This should reduce complexity some, since both latter methods have essentially the same responsibility.
def time_string(time_obj, meridian=true)
if time_obj
str = "%l:%M"
str += " %p" if meridian
time_obj.strftime(str).lstrip
else
""
end
endThis should reduce complexity some, since both latter methods have essentially the same responsibility.
Code Snippets
def time_string(time_obj, meridian=true)
if time_obj
str = "%l:%M"
str += " %p" if meridian
time_obj.strftime(str).lstrip
else
""
end
endContext
StackExchange Code Review Q#19796, answer score: 3
Revisions (0)
No revisions yet.