conversions.rb 1.6 KB
Newer Older
1
require 'date'
2
require 'active_support/core_ext/time/publicize_conversion_methods'
3
require 'active_support/core_ext/time/calculations'
4

5
class String
X
Xavier Noria 已提交
6 7
  # Returns the codepoint of the first character of the string, assuming a
  # single-byte character encoding:
X
Xavier Noria 已提交
8
  #
X
Xavier Noria 已提交
9 10
  #   "a".ord # => 97
  #   "à".ord # => 224, in ISO-8859-1
X
Xavier Noria 已提交
11
  #
X
Xavier Noria 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
  # This method is defined in Ruby 1.8 for Ruby 1.9 forward compatibility on
  # these character encodings.
  #
  # <tt>ActiveSupport::Multibyte::Chars#ord</tt> is forward compatible with
  # Ruby 1.9 on UTF8 strings:
  #
  #   "a".mb_chars.ord # => 97
  #   "à".mb_chars.ord # => 224, in UTF8
  #
  # Note that the 224 is different in both examples. In ISO-8859-1 "à" is
  # represented as a single byte, 224. In UTF8 it is represented with two
  # bytes, namely 195 and 160, but its Unicode codepoint is 224. If we
  # call +ord+ on the UTF8 string "à" the return value will be 195. That is
  # not an error, because UTF8 is unsupported, the call itself would be
  # bogus.
27 28
  def ord
    self[0]
29
  end unless method_defined?(:ord)
J
Jeremy Kemper 已提交
30

31 32
  # Form can be either :utc (default) or :local.
  def to_time(form = :utc)
33 34 35
    d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction).map { |arg| arg || 0 }
    d[6] *= 1000000
    ::Time.send("#{form}_time", *d)
36
  end
37

38 39 40
  def to_date
    ::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday))
  end
J
Jeremy Kemper 已提交
41

42
  def to_datetime
43 44 45
    d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :sec_fraction).map { |arg| arg || 0 }
    d[5] += d.pop
    ::DateTime.civil(*d)
46
  end
J
Jeremy Kemper 已提交
47
end