Defining custom functions to use in views


#1

Hi all,
I am new to rails, so please forget this newbie question…
I would like to add a function for calculating the elapsed time from
the date of a post and the moment when the page is retrieved (Yes, I
am sure 1milion of people did it already…) Considering that it should
only process the data retrieved trough the model and controller, I
would prefer to implement it as a simple utility function and not as a
method of the controller. So, the question is: is there a proper way
to add simple functions and have them accessible within the .rhtml
templates scope?

Thanks,
Andrea


#2

Hemm… I just discovered the existence of the app/helpers folder
and it seems it does what I was looking for…

:wink:


#3

You might look at Rails’ time_ago_in_words (also known as
distance_of_time_in_words_to_now).

Assuming you have a created_at field in your Post model, you can do:

This was posted <%= time_ago_in_words(@post.created_at) %> ago.