ActiveRecord解析到datetime的字符串? [英] ActiveRecord parse string to datetime?

查看:137
本文介绍了ActiveRecord解析到datetime的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在创建新的AR对象时将 String 转换为 Datetime 列,那么它将自动解析: / p>

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 方法到 String 。它的来源很简单:

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 是Ruby的本机(同样的方法由 Date.parse ),它的实际工作完成

Date._parse is native to Ruby (the same method is called by Date.parse) and it's where the real work is done.

它首先使用正则表达式从字符串中除去无关的符号,然后将其传递给其他方法,如 _parse_eu _parse_iso _parse_dot 等等。它们中的每一个都使用自己的正则表达式和其他方法来查看它是否是它理解的日期,并从中提取有意义的信息。一旦其中一个工作(即返回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.

该文档称之为启发式方法,可以将其视为意味着在墙看什么棒它的文件很差,但效果非常好。

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解析到datetime的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆