Formatting time between Rails and Javascript -- avoiding duplicating code across languages
I have a view that takes a Ruby Date, performs some formatting on it to output just the time in the format [5:30 P开发者_StackOverflow中文版M]. Then by default it adds 30 minutes to that so the result is similar to the following output:
5:30 PM - 6:00 PM
and the code in the haml file looks like:
=format_time( @time ) + " - " + format_time( Time.parse( @time ).advance( :minutes => 30 ) )
where format_time is a method I created.
But then the user can change the 'duration' by changing a combobox selection. Let's say the user chooses '60' in the combobox, I need to the add 60 minutes to the start time and update the output to read:
5:30 PM - 6:30 PM
The problem is that when the page first loads, the formatting happens in my Ruby method format_time. But after the combobox selection I think the formatting has to be done in Javascript triggered by the 'onchange' event on the combobox. But that means I have to maintain two different methods to do the same formatting.
Is there a better solution to this?
One option is the have the javascript send out an AJAX request to some rails page whose sole job is to format the date using the same method as before.
Do all the formatting in javascript. Have the haml output the unformatted time as a javascript variable, then format and display it with javascript. That will avoid extra AJAX calls and let you keep the formatting code in exactly one place.
精彩评论