Recently for a project I ran into a quandary when it came down to formating a Date column from the database. In this project most of my dates where being stored as Datetime fields, but for these fields I didn't feel the time was necessary, so I used the smaller Date field. I had already written standard formatting functions as shown in all the basic ruby examples. For instance:
Formatting Function in Envivornment.rb
#My Date Formats
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
:display => "%B %d, %Y"
)
And so far all my formatting was working just fine. But when I loaded up my new form with my newly formatted Date fields in it, I noticed that the formatting had not been applied. I double checked and sure enough the formatting something was wrong.
After looking back at my Environment.rb file I noticed that the formatting rules were being applied to the Time class. After adding a quick debug check I noticed that the Datetime fields were showing a class of Time and the Date fields were showing a class of Date. This was my problem, and now that I knew what was wrong I set out to fix it.
Solution:
This problem has multiple ways to fix it, and I actually went down two different paths. Both of these solutions worked just as well, so really it comes down to coding style on which one works for you.
1) My first attempt was a simple solution (or so I thought) where I just created a function in the Helpers/Application.rb file to format the string using the <object>.strftime function. I could still use the same formating string that I was using before, but now both Date's and Time's where being formatted correctly.
Example 1:
def format_short_date(val)
return val.strftime('%B %d, %Y')
end
2) My second attempt was actually creating a new set of extensions in the Environment.rb file that extended the Date class not the Time class. One note, if you are changing the Environment.rb file make sure to restart your application to have the changes take effect.
Example 2:
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
:display => "%B %d, %Y"
)
Conclusion:
Both ways worked equally well, but for my purposes I choose the second method as I thought it was cleaner solution for me. But I could equally argue that keeping multiple sets of the same extensions around in a file will become a source of frustration when I have to change something. At that time, I am sure I will wonder if my function wasn't the best way to go.
Comments