class Sequel::Postgres::IntervalDatabaseMethods::Parser
Creates callable objects that convert strings into ActiveSupport::Duration instances.
Constants
- SECONDS_PER_MONTH
- SECONDS_PER_YEAR
- USE_PARTS_ARRAY
Whether ActiveSupport::Duration.new takes parts as array instead of hash
Public Instance Methods
call(string)
click to toggle source
Parse the interval input string into an ActiveSupport::Duration instance.
# File lib/sequel/extensions/pg_interval.rb 85 def call(string) 86 raise(InvalidValue, "invalid or unhandled interval format: #{string.inspect}") unless matches = /\A([+-]?\d+ years?\s?)?([+-]?\d+ mons?\s?)?([+-]?\d+ days?\s?)?(?:(?:([+-])?(\d{2,10}):(\d\d):(\d\d(\.\d+)?))|([+-]?\d+ hours?\s?)?([+-]?\d+ mins?\s?)?([+-]?\d+(\.\d+)? secs?\s?)?)?\z/.match(string) 87 88 value = 0 89 parts = {} 90 91 if v = matches[1] 92 v = v.to_i 93 value += SECONDS_PER_YEAR * v 94 parts[:years] = v 95 end 96 if v = matches[2] 97 v = v.to_i 98 value += SECONDS_PER_MONTH * v 99 parts[:months] = v 100 end 101 if v = matches[3] 102 v = v.to_i 103 value += 86400 * v 104 parts[:days] = v 105 end 106 if matches[5] 107 seconds = matches[5].to_i * 3600 + matches[6].to_i * 60 108 seconds += matches[8] ? matches[7].to_f : matches[7].to_i 109 seconds *= -1 if matches[4] == '-' 110 value += seconds 111 parts[:seconds] = seconds 112 elsif matches[9] || matches[10] || matches[11] 113 seconds = 0 114 if v = matches[9] 115 seconds += v.to_i * 3600 116 end 117 if v = matches[10] 118 seconds += v.to_i * 60 119 end 120 if v = matches[11] 121 seconds += matches[12] ? v.to_f : v.to_i 122 end 123 value += seconds 124 parts[:seconds] = seconds 125 end 126 127 # :nocov: 128 if USE_PARTS_ARRAY 129 parts = parts.to_a 130 end 131 # :nocov: 132 133 ActiveSupport::Duration.new(value, parts) 134 end