简体   繁体   English

Rails ActiveSupport扩展了to_date,to_datetime,to_time

[英]Rails ActiveSupport extending to_date, to_datetime, to_time

The application I'm working with insists on displaying all user-input dates (via jquery datepicker) in the non standard American %m/%d/%Y format. 我正在使用的应用程序坚持以非标准的美国%m /%d /%Y格式显示所有用户输入的日期(通过jquery datepicker)。 As a result we have a lot of strptime methods scattered throughout our controllers. 结果,我们在控制器中分散了许多strptime方法。

I'm trying to clean it up and would like to overload the Rails to_date, to_datetime, and to_time extensions so these are no longer necessary. 我正在尝试清理它,并希望重载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

Anyway, this works great in rails console; 无论如何,这在Rails控制台中效果很好。 "06/24/2014".to_date and variants behave exactly as I would like them. “ 06/24/2014” .to_date和变体的行为完全符合我的要求。 However, it looks like ActiveRecord doesn't use these overloaded definitions when creating/validating new table entries, eg 但是,看起来ActiveRecord在创建/验证新表条目时未使用这些重载定义,例如

MyModelName.create(start_date:"06/07/2014") gives a start date of 2014-07-06. MyModelName.create(start_date:"06/07/2014")给出开始日期为2014-07-06。

What can I do to make ActiveRecord recognize these overloaded definitions? 如何使ActiveRecord识别这些重载定义?

You can set default time and date formats in config/application.rb file this way: 您可以通过以下方式在config / application.rb文件中设置默认时间和日期格式:

my_date_formats = { :default => '%d.%m.%Y' }
Time::DATE_FORMATS.merge!(my_date_formats) 
Date::DATE_FORMATS.merge!(my_date_formats)

The ruby-american_date gem may be what you want. ruby-american_date宝石可能就是您想要的。 It forces Date/DateTime/Time.parse to parse American formatted dates. 它强制Date / DateTime / Time.parse解析美国格式的日期。 Simply include it in your project's Gemfile. 只需将其包含在项目的Gemfile中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM