Class: ConceptQL::DateAdjuster

Inherits:
Object
  • Object
show all
Defined in:
lib/conceptql/date_adjuster.rb

Overview

Used to translate a string of terse date adjustments into a set of adjustments that are compatible with most RDBMSs

Constant Summary collapse

VALID_INPUT =
/\A#{Regexp.union([/START/i, /END/i, /\d{4}-\d{2}-\d{2}/, /([-+]?\d+[dmy]?)+/, /\s*/])}\z/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str, opts = {}) ⇒ DateAdjuster

Returns a new instance of DateAdjuster.



10
11
12
13
# File 'lib/conceptql/date_adjuster.rb', line 10

def initialize(str, opts = {})
  @str = str || ""
  @manipulator = opts[:manipulator] || Sequel
end

Instance Attribute Details

#strObject (readonly)

Returns the value of attribute str.



9
10
11
# File 'lib/conceptql/date_adjuster.rb', line 9

def str
  @str
end

Instance Method Details

#adjust(column, reverse = false) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/conceptql/date_adjuster.rb', line 20

def adjust(column, reverse=false)
  return Sequel.expr(:end_date) if str.downcase == 'end'
  return Sequel.expr(:start_date) if str.downcase == 'start'
  return Sequel.cast(Date.parse(str).strftime('%Y-%m-%d'), Date) if str =~ /^\d{4}-\d{2}-\d{2}$/
  adjusted_date = adjustments.inject(Sequel.expr(column)) do |sql, (units, quantity)|
    quantity *= -1 if reverse
    if quantity > 0
      manipulator.date_add(sql, units => quantity)
    else
      manipulator.date_sub(sql, units => quantity.abs)
    end
  end
  Sequel.cast(adjusted_date, Date)
end

#adjustmentsObject

Returns an array of strings that represent date modifiers



16
17
18
# File 'lib/conceptql/date_adjuster.rb', line 16

def adjustments
  @adjustments ||= parse(str)
end