This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
require 'time'
|
||||
|
||||
module SafeYAML
|
||||
class Parse
|
||||
class Date
|
||||
# This one's easy enough :)
|
||||
DATE_MATCHER = /\A(\d{4})-(\d{2})-(\d{2})\Z/.freeze
|
||||
|
||||
# This unbelievable little gem is taken basically straight from the YAML spec, but made
|
||||
# slightly more readable (to my poor eyes at least) to me:
|
||||
# http://yaml.org/type/timestamp.html
|
||||
TIME_MATCHER = /\A\d{4}-\d{1,2}-\d{1,2}(?:[Tt]|\s+)\d{1,2}:\d{2}:\d{2}(?:\.\d*)?\s*(?:Z|[-+]\d{1,2}(?::?\d{2})?)?\Z/.freeze
|
||||
|
||||
SECONDS_PER_DAY = 60 * 60 * 24
|
||||
MICROSECONDS_PER_SECOND = 1000000
|
||||
|
||||
# So this is weird. In Ruby 1.8.7, the DateTime#sec_fraction method returned fractional
|
||||
# seconds in units of DAYS for some reason. In 1.9.2, they changed the units -- much more
|
||||
# reasonably -- to seconds.
|
||||
SEC_FRACTION_MULTIPLIER = RUBY_VERSION == "1.8.7" ? (SECONDS_PER_DAY * MICROSECONDS_PER_SECOND) : MICROSECONDS_PER_SECOND
|
||||
|
||||
# The DateTime class has a #to_time method in Ruby 1.9+;
|
||||
# Before that we'll just need to convert DateTime to Time ourselves.
|
||||
TO_TIME_AVAILABLE = DateTime.instance_methods.include?(:to_time)
|
||||
|
||||
def self.value(value)
|
||||
d = DateTime.parse(value)
|
||||
|
||||
return d.to_time if TO_TIME_AVAILABLE
|
||||
|
||||
usec = d.sec_fraction * SEC_FRACTION_MULTIPLIER
|
||||
time = Time.utc(d.year, d.month, d.day, d.hour, d.min, d.sec, usec) - (d.offset * SECONDS_PER_DAY)
|
||||
time.getlocal
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,12 @@
|
||||
module SafeYAML
|
||||
class Parse
|
||||
class Hexadecimal
|
||||
MATCHER = /\A[-+]?0x[0-9a-fA-F_]+\Z/.freeze
|
||||
|
||||
def self.value(value)
|
||||
# This is safe to do since we already validated the value.
|
||||
return Integer(value.gsub(/_/, ""))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,26 @@
|
||||
module SafeYAML
|
||||
class Parse
|
||||
class Sexagesimal
|
||||
INTEGER_MATCHER = /\A[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\Z/.freeze
|
||||
FLOAT_MATCHER = /\A[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\.[0-9_]*\Z/.freeze
|
||||
|
||||
def self.value(value)
|
||||
before_decimal, after_decimal = value.split(".")
|
||||
|
||||
whole_part = 0
|
||||
multiplier = 1
|
||||
|
||||
before_decimal = before_decimal.split(":")
|
||||
until before_decimal.empty?
|
||||
whole_part += (Float(before_decimal.pop) * multiplier)
|
||||
multiplier *= 60
|
||||
end
|
||||
|
||||
result = whole_part
|
||||
result += Float("." + after_decimal) unless after_decimal.nil?
|
||||
result *= -1 if value[0] == "-"
|
||||
result
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user