On Wednesday 07 September 2005 00:49, Steve Ross wrote:> My application is built on Rails and MySQL. It will only be accepting
> US formatted dates as input, however both Rails and MySQL are
> oriented around ISO the format. I know I can convert a good portion
> of the entries using ParseDate::parsedate but it does not appear this
> is how the conversion is taking place when data is being transferred
> from the params hash into model members.
I''ve had to deal with this recently, too. Although I want to be able to
handle dates of different formats. The module below is a mixin for
ActiveRecord. To activate it, in environment.rb, say, insert
ActiveRecord::Base.class_eval do
include BoilerPlate::Model::I18n
end
Adapt it to your needs and taste.
HTH,
Michael
require ''active_record''
require ''date''
module BoilerPlate # :nodoc:
module Model # :nodoc:
# I18n support for ActiveRecord.
# Currently, all that it does is define a class variable
#
# ActiveRecord::Base.date_format
#
# and redefines +write_attribute+ to convert string values to dates
# according to this format.
module I18n
def self.included(base)
base.class_eval do
unless method_defined?(:write_attribute_with_date_cast)
alias_method :write_attribute_without_date_cast, :write_attribute
def write_attribute_with_date_cast(attr, value)
if column_for_attribute(attr).type == :date
value = cast_to_date(value)
end
write_attribute_without_date_cast(attr, value)
end
alias_method :write_attribute, :write_attribute_with_date_cast
cattr_accessor :date_format
ActiveRecord::Base.date_format = ''%Y-%m-%d''
end
end
end
protected
def cast_to_date(value)
case value
when String
Date.strptime(value, ActiveRecord::Base.date_format) rescue
nil ### FIXME rescue better
when Date, Time
value
else
raise ArgumentError, "Argument to cast_to_date must be a
String, Date, or Time; was: #{value.inspect}"
end
end
end
end
end
--
Michael Schuerig Nothing is as brilliantly adaptive
mailto:michael-q5aiKMLteq4b1SvskN2V4Q@public.gmane.org as selective
stupidity.
http://www.schuerig.de/michael/ --A.O. Rorty, The Deceptive Self