Rails: Is there a built translation for "ago"?

Viewed 510

Rails translate time ago with time_ago_in_words and documentation is this.

time_ago_in_words(3.minutes.from_now)                 # => 3 minutes

However, in our app, we use "ago": 3 minutes ago

So, what is the best way to translate when "ago" appears before the time_ago, such as in French:

Il y a 3 minutes

Is this built into Rails?

Using Rails 4.2.10 and rails-i18n gem which provides the distance in time, but not the "ago".

2 Answers

You could use custom scopes:

https://github.com/rails/rails/blob/fc5dd0b85189811062c85520fd70de8389b55aeb/actionview/lib/action_view/helpers/date_helper.rb#L75

time_ago_in_words(3.minutes.ago, scope: 'datetime.distance_in_words_ago') # => 3 minutes ago

and you need to add this to your locale (en.yml)

en:
  datetime:
    distance_in_words_ago:
      x_days:
        one: 1 day ago
        other: "%{count} days ago"
      x_minutes:
        one: 1 minute ago
        other: "%{count} minutes ago"
      x_months:
        one: 1 month ago
        other: "%{count} months ago"
      x_years:
        one: 1 year ago
        other: "%{count} years ago"
      x_seconds:
        one: 1 second ago
        other: "%{count} seconds ago"

https://github.com/rails/rails/blob/fc5dd0b85189811062c85520fd70de8389b55aeb/actionview/lib/action_view/helpers/date_helper.rb#L78

I think you just need to pass the time as a variable to the translation. Then in the language ymls, you can have the rest of the string where it needs to be.

Suppose that @product.purchased_time_ago returns the time_ago_in_words().

# app/views/products/show.html.erb
<%= t('time_ago', time: @product.purchased_time_ago) %>

# config/locales/en.yml
en:
  time_ago: "%{time} ago"

# config/locales/fr.yml
fr:
  time_ago: "Il y a %{time}"

This is direct taken from the docs.

Related