0
  def short_remaining_time
    difference  = Time.diff(Time.now, created_at + 7.days, '%d - %H - %N')

    # To display the short remaining time in an auction listing.
    if difference[:day] == 0 and difference[:hour] >= 1
      "#{difference[:minute]} minutos"
    elsif difference[:day] == 0 and difference[:hour] >= 23
      "#{difference[:hour]} horas"
    else
      if difference[:day] != 1
        "#{difference[:day]} dias"
      else
        "#{difference[:day]} dia"
      end
    end
  end

This method is inside my auction.rb model in my Rails application.

In one of my views, I am listing all auctions in the system, and I also display how much time is remaining before the auction closes.

Depending on the amount of time, I either show the days hours or minutes.

The code is working fine, just looks and feels very clunky. Is there a way to spruce this up a bit?

sergserg
  • 21,716
  • 41
  • 129
  • 182

3 Answers3

1

You can simplify it as below. Note that your code is redundant. If difference[:hour] >= 23, then that entails difference[:hour] >= 1, and will be captured by the latter, so the former condition will never be evaluated to true. So that part can be removed.

def short_remaining_time
  difference  = Time.diff(Time.now, created_at + 7.days, '%d - %H - %N')
  case day = difference[:day]
  when 0
    if difference[:hour] >= 1 then "#{difference[:minute]} minutos"
    else "#{day} dias"
    end
  when 1 then "#{day} dia"
  else "#{day} dias"
  end
end
sawa
  • 165,429
  • 45
  • 277
  • 381
1

I assume you got your inequalities unintentionally not quite right (you need <= not >=). Also, if you assume that the hours in the difference will always be no more than 23, you don't need that check (i.e., we're assuming the time difference is "normalized"). So I'd modify it this way to keep your original intent:

  def short_remaining_time
    difference  = Time.diff(Time.now, created_at + 7.days, '%d - %H - %N')

    # To display the short remaining time in an auction listing.
    if difference[:day] == 0
      if difference[:hour] <= 1
        "#{difference[:minute]} minutos"
      else
        "#{difference[:hour]} horas"
      end
    else
      "#{difference[:day]} dia" + ((difference[:day] == 1) ? "" : "s")
    end
  end
lurker
  • 56,987
  • 9
  • 69
  • 103
  • I'm getting this error: `no implicit conversion of nil into String`. It's trying to convert `nil` into a string if `difference[:day]` is not 1. – sergserg Aug 17 '13 at 02:04
1

What about

def short_remaining_time
  difference      = Time.diff(Time.now, created_at + 7.days, '%d - %H - %N')
  diff_in_minutes = difference[:day] * 3600 + difference[:hour] * 60

  case diff_in_minutes
    when 0..60      then  "#{difference[:minute]} minutos"
    when 61..3600   then  "#{difference[:hour]  } horas"
    when 3600..7200 then  "#{difference[:day]   } dia"
    else                  "#{difference[:day]   } dias"
  end
end
hirolau
  • 13,451
  • 8
  • 35
  • 47