我正在使用的應用程序堅持要求顯示非標準美國%m /%d /%Y格式的所有用戶輸入日期(通過jquery datepicker)。因此我們有很多分散在我們控制器中的strptime
方法。Rails ActiveSupport擴展to_date,to_datetime,to_time
我想清理它,並想重載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
無論如何,這在軌道控制檯很好用; 「2014/6/24」.to_date和變體的行爲完全符合我的願望。但是,看起來ActiveRecord在創建/驗證新表項時不使用這些重載定義,例如
MyModelName.create(start_date:"06/07/2014")
給出了2014-07-06的開始日期。
我該怎麼做才能讓ActiveRecord識別這些重載的定義?
您知道jQuery-UI datepicker可以一次使用[兩種格式](http://api.jqueryui.com/datepicker/#option-altFormat),對不對?用戶界面可以做任何想做的事情,但所有與服務器的通信都應該使用明智的ISO 8601格式。 –
您不應該真的改變內置方法的含義。添加你自己的應該是可以接受的,但它也不是必需的。 –