Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...