Date.parse handling YY format incorrectly

3 views
Skip to first unread message

Finding_Zion

unread,
May 29, 2009, 11:43:05 AM5/29/09
to ChicagoRuby.org
As part of my Production Schedule Application, I'm saving a lot of
dates for projects. When a date like "12/01/09" is saved, it is
becoming "12/01/0009". I figured a way to fix this, but I wondered if
there was a better way.

In application_helper.rb, I added the following to override the
Date.parse method.

class Date
def self.parse(str, comp=true, sg=ITALY)
elem = _parse(str, comp)
new_by_frags(elem, sg)
end
end

The only difference for the declaration, is the "comp=true". It's
turned off by default. There has to be a better way, what do you guys
think?

Jeremy

kim chirnside

unread,
May 31, 2009, 5:24:05 PM5/31/09
to ChicagoRuby.org
I tend to think that to be a dangerous approach. Overriding a core
method like parse may affect any number of rails plugins, core rails
code and your own code, which may not be aware of this change.
You can probably vouch for your own code, if your the only one writing
it, but if it needs to be supported by someone else, then things can
get messy.

It's not clear on your reasoning for not just using the optional
second argument when you are calling Date.parse, but I'm sure there is
a good one. So I can only suggest making a specialised version of the
method. If you don't like the default arguments and you don't want to
pass the argument, I'd recommend writing another method that assumes
the value of that argument. eg.

class Date
def self.parse_modern(str, *args)
return parse(str, args.unshift(true))
end
end

That leaves all plugins/libraries/legacy code happily using
Date.parse. You can now start using Date.parse_modern(str). Of
course, assuming you don't want to just use Date.parse(str, true).

Where to put it? Don't know whether application_helper.rb is quite
the place to put it. You've changed a library that is accessible to
the entire rails stack, so loading it in a helper sounds misleading.
I'd recommend writing it in lib/ and loading it when rails boots.
Then there's no question as to which version the entire rails app
sees.

Well that's some thoughts anyway. Hope it's a worthwhile read.

Kim

Finding_Zion

unread,
Jun 1, 2009, 9:02:43 AM6/1/09
to ChicagoRuby.org
Thanks Kim, I received a direct reply referring to my implementation
as a Monkey Patch. I decided to rethink my current implementation and
found the models that call the parse method directly. I didn't
realize that they were being called on these models, much to my
dismay. Now, after reworking it, I removed it from my
application_helper and it is much dryier.

Jeremy
Reply all
Reply to author
Forward
0 new messages