我正在使用的应用程序坚持以非标准美国 %m/%d/%Y 格式显示所有用户输入日期(通过 jquery datepicker)。因此,我们有很多strptime
方法分散在我们的控制器中。
我正在尝试清理它,并希望重载 Rails 的 to_date、to_datetime 和 to_time 扩展,因此不再需要这些扩展。
#config/initializers/string.rb
class String
def to_date
begin
Date.strptime(self, '%m/%d/%Y') #attempt to parse in american format
rescue ArgumentError
Date.parse(self, false) unless blank? #if an error, execute original Rails to_date
#(pulled from Rails source)
end
end
def to_datetime
begin
DateTime.strptime(self,'%m/%d/%Y')
rescue ArgumentError
DateTime.parse(self, false) unless blank?
end
end
def to_time(form = :local)
begin
Time.strptime(self,'%m/%d/%Y')
rescue ArgumentError
parts = Date._parse(self, false)
return if parts.empty?
now = Time.now
time = Time.new(
parts.fetch(:year, now.year),
parts.fetch(:mon, now.month),
parts.fetch(:mday, now.day),
parts.fetch(:hour, 0),
parts.fetch(:min, 0),
parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
parts.fetch(:offset, form == :utc ? 0 : nil)
)
form == :utc ? time.utc : time.getlocal
end
end
end
无论如何,这在 Rails 控制台中效果很好;"06/24/2014".to_date 和变体的行为完全符合我的意愿。但是,看起来 ActiveRecord 在创建/验证新表条目时不使用这些重载定义,例如
MyModelName.create(start_date:"06/07/2014")
给出的开始日期为 2014-07-06。
我可以做些什么来让 ActiveRecord 识别这些重载的定义?