class Sequel::Postgres::IntervalDatabaseMethods::Parser

Creates callable objects that convert strings into ActiveSupport::Duration instances.

Constants

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
 75 def call(string)
 76   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)
 77 
 78   value = 0
 79   parts = {}
 80 
 81   if v = matches[1]
 82     v = v.to_i
 83     value += 31557600 * v
 84     parts[:years] = v
 85   end
 86   if v = matches[2]
 87     v = v.to_i
 88     value += 2592000 * v
 89     parts[:months] = v
 90   end
 91   if v = matches[3]
 92     v = v.to_i
 93     value += 86400 * v
 94     parts[:days] = v
 95   end
 96   if matches[5]
 97     seconds = matches[5].to_i * 3600 + matches[6].to_i * 60
 98     seconds += matches[8] ? matches[7].to_f : matches[7].to_i
 99     seconds *= -1 if matches[4] == '-'
100     value += seconds
101     parts[:seconds] = seconds
102   elsif matches[9] || matches[10] || matches[11]
103     seconds = 0
104     if v = matches[9]
105       seconds += v.to_i * 3600
106     end
107     if v = matches[10]
108       seconds += v.to_i * 60
109     end
110     if v = matches[11]
111       seconds += matches[12] ? v.to_f : v.to_i
112     end
113     value += seconds
114     parts[:seconds] = seconds
115   end
116 
117   # :nocov:
118   if USE_PARTS_ARRAY
119     parts = parts.to_a
120   end
121   # :nocov:
122 
123   ActiveSupport::Duration.new(value, parts)
124 end