【发布时间】:2014-06-24 18:25:33
【问题描述】:
我正在使用的应用程序坚持以非标准美国 %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 识别这些重载的定义?
【问题讨论】:
-
你知道jQuery-UI datepicker 可以使用two formats at once,对吧? UI 可以为所欲为,但与服务器之间的所有通信都应使用合理的 ISO 8601 格式。
-
您不应该真正改变内置方法的含义。添加你自己的应该是可以接受的,但也不是必须的。
标签: ruby-on-rails ruby activerecord activesupport to-date