Search code examples
ruby-on-railsdatetimehelpermethods

Rails distance_of_time_in_words_to_now options


I'm guessing I need to create a helper method to achieve this, but essentially I'd like to use distance_of_time_in_words_to_now to display the time between a datetime field's data and now, but in more specific words. For instance, if it's 3 days it should say "in 3 days". If it's tomorrow, it should say "tomorrow" (without the word "in").

All I currently have is:

<%= distance_of_time_in_words_to_now(interaction.action_date) %>

Any points in the right direction here? Thanks!


Solution

  • If you check out the source of this method (http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words) you will see it uses localization. The key for days is :x_days, so in your en.yml file, you can override that, using :count, like the following:

    en:
      x_days: "in %{count} days"
    

    Now for "tomorrow", I would create a helper that either returns your custom responses or fallsback to distance_of_time_in_words, like so:

    def custom_distance_of_time_in_words_to_now(time)
      return "tomorrow" if time.tomorrow? #however you decide to check
      distance_of_time_in_words_to_now(time)
    end