How can I use the rails helper "distance_of_time_in_words" in plain old ruby (non-rails)

Michael Durrant picture Michael Durrant · Mar 5, 2012 · Viewed 14.1k times · Source

Rails has an helper which converts distance of time in words using distance_of_time_in_words

What do I need to include if I am just using ruby at the irb prompt to get this function?

I tried require 'action_view' but it didn't help.

I also tried require 'active_support/core_ext' but that didn't help either.

Answer

TheDelChop picture TheDelChop · Mar 5, 2012

This should work:

require 'action_view'

include ActionView::Helpers::DateHelper

Both of these need to be done for a couple of reasons. First, you need to require the library, so that its modules and methods are available to be called. This is why you need to do require 'action_view'.

Second, since distance_of_time_in_words is module, which does not stand on its own, it needs to be included in class. You can then access it by calling distance_of_time_in_words on an instance of that class.

When you are in the console, you already have an instance of the Object class running. You can verify this by calling self in the irb console. When you call include ActionView::Helpers::DateHelper, you are including those methods for any instance of the Object class. Since that is the implicit receiver of the irb console, you can then just save distance_of_time_in_words right on the console and get what you want!

Hope that helps.

Joe