Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Rails DateHelper method time_ago_in_words outside of Rails?

Tags:

So, I downloaded and installed the ActiveHelper gem, but I still can't figure out how to use ActionView's DateHelper methods, such as time_ago_in_words, in normal Ruby code. Is this not included in ActiveHelper? Is it possible to use these methods outside of Rails?

http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-time_ago_in_words

like image 533
user1796160 Avatar asked Feb 23 '15 04:02

user1796160


1 Answers

Try this:

require 'action_view'
require 'action_view/helpers'
include ActionView::Helpers::DateHelper
time_ago_in_words(Time.now - 60*60*2) + ' ago'
#=> "about 2 hours ago"

If you need to take advantage of Numeric ActiveSupport extensions:

require 'active_support/core_ext/numeric/time'
time_ago_in_words(Time.now - 2.hours) + ' ago'
#=> "about 2 hours ago"
# note that (Time.now - 2.hours) == (2.hours.ago)

Reference for Non Rails App : https://github.com/elgalu/time_ago_in_words#non-rails-apps

like image 66
Gagan Gami Avatar answered Oct 03 '22 00:10

Gagan Gami