HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Presenting a time as a string

Submitted by: @import:stackexchange-codereview··
0
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:

# 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
end


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?

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:

def time_string(time_obj, meridian=true)
  if time_obj
    str = "%l:%M"
    str += " %p" if meridian
    time_obj.strftime(str).lstrip
  else
    ""
  end
end


This 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
end

Context

StackExchange Code Review Q#19796, answer score: 3

Revisions (0)

No revisions yet.