ActiveRecord的解析字符串日期时间? [英] ActiveRecord parse string to datetime?
问题描述
如果我通过字符串
到日期时间
列,同时创造新的AR对象时,它会自动解析:
If I pass a String
into Datetime
column while creating new AR object, it will be automatically parse:
1.9.2p290 :011 > Movie.new(:release_date=>"21-Nov-1990")
=> #<Movie id: nil, release_date: "1990-11-21 00:00:00", created_at: nil, updated_at: nil>
如何的Rails
或的ActiveRecord
,做到这一点魔法?哪种方法不会使用?
How does Rails
, or ActiveRecord
, do this magic? Which method does it use?
推荐答案
Rails添加一个 TO_DATE
方法字符串
。它的来源很简单:
Rails adds a to_date
method to String
. Its source is simple:
# File activesupport/lib/active_support/core_ext/string/conversions.rb, line 42
def to_date
return nil if self.blank?
::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday))
end
Date._parse
原产于红宝石(同样的方法被称为 Date.parse
),它的< A HREF =http://apidock.com/ruby/Date/_parse/class>其中真正的工作是做的。
Date._parse
is native to Ruby (the same method is called by Date.parse
) and it's where the real work is done.
它首先使用正则EX pression从字符串删除多余的符号,然后将其传递到其他的方法,如 _parse_eu
, _parse_iso
, _parse_dot
等。每个这些使用其自己的正常前pressions等方法,看它是否是它理解并从中提取的有意义的信息的日期。一旦其中的一个作品(即返回true),其余被跳过。最后,早在 _parse
,所提取的信息来建立一个日期和时间,做更多的工作,以找出像检查的一周内有无一天对12一年价值应该是指1912年或2012年。
It first uses a regular expression to remove extraneous symbols from the string, then passes it to other methods like _parse_eu
, _parse_iso
, _parse_dot
and so on. Each of these uses its own regular expressions and other methods to see if it's a date that it understands and extract the meaningful information from it. Once one of them "works" (i.e. returns true), the rest are skipped. Finally, back in _parse
, the extracted information is used to build a date and time, doing a little more work to figure out things like checking for the day of the week and whether a year value of "12" should mean 1912 or 2012.
该文档称这是一个启发式的方法,它可以被理解为它抛出一堆可能性墙上看到什么坚持。这是pretty的不良的记录,但运作得非常好。
The docs call this a heuristic method, which could be taken to mean it throws a bunch of possibilities at the wall to see what sticks. It's pretty poorly-documented but works remarkably well.
这篇关于ActiveRecord的解析字符串日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!