30

I have a datetime attribute on a record:

 1.9.3p194 :024> f.last_contact
 => Thu, 11 Aug 2011 00:00:00 UTC +00:00 

But when I try time_ago_in_words at the console, it doesn't work:

> time_ago_in_words(f.last_contact)
NoMethodError: undefined method `time_ago_in_words' for main:Object

I also tried distance_of_time_in_words which the docs say should work with Time, Date & DateTime objects.

> to_time = Time.now
 => 2012-09-08 12:22:16 -0500 
> distance_of_time_in_words(f.last_contact, to_time)
NoMethodError: undefined method `distance_of_time_in_words' for main:Object

What is the cause of this? Shouldn't Rails Console load all the necessary libraries and dependencies for all of Rails methods to work?

marcamillion
  • 32,933
  • 55
  • 189
  • 380

2 Answers2

85

You can use all helpers (built-in and your own) through helper object

helper.time_ago_in_words(1.hour.ago)
=> "about 1 hour"

Or import required helpers

include ActionView::Helpers::DateHelper
time_ago_in_words(1.hour.ago)
=> "about 1 hour" 
dimuch
  • 12,728
  • 2
  • 39
  • 23
8

Try

helper.time_ago_in_words(...)
helper.distance_of_time_in_words(...)

Calling helper. seems to give you access to any/all defined helpers.

More info in this answer: How do I call controller/view methods from the console in Rails?

The reason, I think, that you can't just call the helper directly is because they're not in scope from where you are (in the console), as opposed to code that's running inside a view where the helpers are in scope.

Community
  • 1
  • 1
jefflunt
  • 33,527
  • 7
  • 88
  • 126