Trevan Hetzel
Trevan Hetzel

Reputation: 1369

Rails 3 - More flexible time_ago_in_words

I have this in my view: Due <%= time_ago_in_words(todo.due) %>

But unlike most use cases of time_ago_in_words, I need to support time AGO and time AHEAD. Since a due date can be past due (time ago) and coming up (time ahead), how can I display this conditionally so if it's past due, the above code would output "Due x days ago" and if it's due in the future output "Due in x days"?

Upvotes: 1

Views: 951

Answers (4)

sameera207
sameera207

Reputation: 16629

If you are do deal with natural language date time parsing, I recommend chronic gem

it has many ways of date time parsing

HTH

Upvotes: 0

Michael Durrant
Michael Durrant

Reputation: 96484

In your model have:

class Someclass < ActiveRecord::Base

attr_reader :time_diff

def time_diff
    time_difference = 
      if todo.due > Time.new()
        todo - Time.new()
      else
        Time.new() - todo.due
      end
    end
    time_difference.strftime("%I:%M%p")  # This gets returned.  
end

In your view:

<%= time_in_words(@db_record.time_diff) %>

Where @db_record is a row in the database table for the model in question.

Upvotes: 1

Egryan
Egryan

Reputation: 717

from the looks of it you are using the erb template engine, you can do if conditions in the view logic by obmitting the = sign So you can do something like this

<% if time_ago < Time.now %>
<%= time_ago_in_words(todo.due) %>
<% else %>
<%= time_ahead_in_words(todo.due) %>
<% end %>

should give you a idea on what to do. Though I believe a better practice would be to probably move this to the models portion of your rails app. I common axiom is Fat Models skinny controllers, but that's more advice then a rule.

EDIT

Has Alex mentioned in a comment below this should probably go in a helper method and not in the model part of the app

Upvotes: 3

Baldrick
Baldrick

Reputation: 24340

You can create you own helper like this:

def time_diff_in_words(from_time)
  # compute days difference from now
  days_delta = (Time.now - from_time) / (24 * 60 * 60)  
  # render text
  days = pluralize(days_delta, 'day')
  days_delta > 0 ? "Due #{days} ago" : "Due in #{days}"       
end

Upvotes: 1

Related Questions