[LRUG] How does Rails decide how to parse ambiguous dates?
Paul Robinson
paul at 32moves.com
Tue Jul 26 03:55:58 PDT 2011
On 26 Jul 2011, at 11:39, John Winters wrote:
> 1) How exactly does Rails interpret a date string typed into a field? What method does it use?
I always assumed it simply hands it off to Date.parse, which in turn hands off to _parse:
http://ruby-doc.org/stdlib/libdoc/date/rdoc/classes/Date.html#M000458
> 2) How does one control this behaviour?
There are helpers, but if they are seeming a bit confusing or you need/want more control, ideally you want to control the input format better, and you should consider cleaning the user input into a coherent date format.
For example, Date.parse is 100% consistent with YYYY-MM-DD, and you could therefore write a couple of methods to wrap around your actual_date field like this:
def user_date
return actual_date.strftime("%d/%m/%Y") if current_user.british?
return actual_date.strftime("%m/%d/%Y") if current_user.american?
...
end
def user_date=(date)
actual_date = Date.parse("#{date[6,4]}-#{date[3,2]}-#{date[0,2}") if current_user.british?
actual_date = Date.parse("#{date[6,4]}-#{date[0,2}-#{date[3,2]}") if current_user.american?
...
end
In your forms, just reference user_date... It's an ugly bodge, but it'll work if the existing methods aren't what you're after.
Paul
More information about the Chat
mailing list