class Sequel::Postgres::IntervalDatabaseMethods::Parser

  1. lib/sequel/extensions/pg_interval.rb
Superclass: Object

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

Methods

Public Instance

  1. call

Constants

SECONDS_PER_MONTH = ActiveSupport::Duration::SECONDS_PER_MONTH  
SECONDS_PER_YEAR = ActiveSupport::Duration::SECONDS_PER_YEAR  
USE_PARTS_ARRAY = !defined?(ActiveSupport::VERSION::STRING) || ActiveSupport::VERSION::STRING < '5.1'  

Whether ActiveSupport::Duration.new takes parts as array instead of hash

Public Instance methods

call(string)

Parse the interval input string into an ActiveSupport::Duration instance.

[show source]
    # File lib/sequel/extensions/pg_interval.rb
 86 def call(string)
 87   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)
 88 
 89   value = 0
 90   parts = {}
 91 
 92   if v = matches[1]
 93     v = v.to_i
 94     value += SECONDS_PER_YEAR * v
 95     parts[:years] = v
 96   end
 97   if v = matches[2]
 98     v = v.to_i
 99     value += SECONDS_PER_MONTH * v
100     parts[:months] = v
101   end
102   if v = matches[3]
103     v = v.to_i
104     value += 86400 * v
105     parts[:days] = v
106   end
107   if matches[5]
108     seconds = matches[5].to_i * 3600 + matches[6].to_i * 60
109     seconds += matches[8] ? matches[7].to_f : matches[7].to_i
110     seconds *= -1 if matches[4] == '-'
111     value += seconds
112     parts[:seconds] = seconds
113   elsif matches[9] || matches[10] || matches[11]
114     seconds = 0
115     if v = matches[9]
116       seconds += v.to_i * 3600
117     end
118     if v = matches[10]
119       seconds += v.to_i * 60
120     end
121     if v = matches[11]
122       seconds += matches[12] ? v.to_f : v.to_i
123     end
124     value += seconds
125     parts[:seconds] = seconds
126   end
127 
128   # :nocov:
129   if USE_PARTS_ARRAY
130     parts = parts.to_a
131   end
132   # :nocov:
133 
134   ActiveSupport::Duration.new(value, parts)
135 end