因此,我下载并安装了ActiveHelper gem,但我仍然无法弄清楚如何在普通的Ruby代码中使用ActionView的DateHelper方法,例如time_ago_in_words。这不包含在ActiveHelper中吗?是否可以在Rails之外使用这些方法?
http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-time_ago_in_words
答案 0 :(得分:24)
试试这个:
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"
如果您需要利用Numeric ActiveSupport扩展程序:
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)
参考非Rails应用: https://github.com/elgalu/time_ago_in_words#non-rails-apps
答案 1 :(得分:3)
我不知道ActiveHelper是什么,但你的基本要求是在非Rails应用程序中提供time_ago_in_words
:
require 'rubygems'
require 'action_view'
include ActionView::Helpers::DateHelper
time_ago_in_words Time.now - 4 * 86400
# => "4 days"
答案 2 :(得分:1)
require 'rubygems'
require 'active_support/core_ext/numeric/time'
require 'action_view'
require 'action_view/helpers'
include ActionView::Helpers::DateHelper
70.minutes.ago
# => 2015-02-23 09:09:04 +0530
time_ago_in_words(3.minutes.from_now)
#=> "3 minutes"