Sha256: 52ae8e24b5f275fc7640459922282ef73827c9670e5e09b20a1d2ffc0a35e9c3

Contents?: true

Size: 1.04 KB

Versions: 6

Compression:

Stored size: 1.04 KB

Contents

require_relative '../conceptql'

module ConceptQL
  # Used to translate a string of terse date adjustments into a set of adjustments that are compatible with most RDBMSs
  class DateAdjuster
    attr :str
    def initialize(str)
      @str = str
    end

    # Returns an array of strings that represent date modifiers
    def adjustments
      @adjustments ||= parse(str)
    end

    private
    def lookup
      {
        'y' => :years,
        'm' => :months,
        'd' => :days
      }
    end

    def parse(str)
      ConceptQL.logger.debug(str)
      return [] if str.nil? || str.empty?
      return [[lookup['d'], str.to_i]] if str.match(/^[-+]?\d+$/)
      str.downcase.scan(/([-+]?\d*[dmy])/).map do |adjustment|
        adjustment = adjustment.first
        quantity = 1
        if adjustment.match(/\d/)
          quantity = adjustment.to_i
        else
          if adjustment.chars.first == '-'
            quantity = -1
          end
        end
        unit = lookup[adjustment.chars.last]
        [unit, quantity]
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
conceptql-0.2.0 lib/conceptql/date_adjuster.rb
conceptql-0.1.1 lib/conceptql/date_adjuster.rb
conceptql-0.1.0 lib/conceptql/date_adjuster.rb
conceptql-0.0.9 lib/conceptql/date_adjuster.rb
conceptql-0.0.8 lib/conceptql/date_adjuster.rb
conceptql-0.0.7 lib/conceptql/date_adjuster.rb