Sha256: 76835c0bf1472da20ce9a1328cdf3ab5c7f8842c7a6dc6de1d68881c7da1b6b6

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 KB

Contents

require 'active_record'

module FirstAfterCreatedAt
  def first_after_created_at(date)
    first_id = first.id
    last_id = last.id
    jump_size = (last_id - first_id) / 2
    center = first_after_id(first_id + jump_size)
    best_distance = 1/0.0
    new_center = nil
    while jump_size != 0
      logger.debug('iterated')
      new_center =
        if center.created_at < date
          # move forward
          first_after_id(center.id + jump_size)
        else
          # move backwards
          first_after_id(center.id - jump_size)
        end


      distance = new_center.created_at - date
      if distance == 0
        return new_center
      elsif distance > 0 && distance < best_distance
        best = new_center
        best_distance = distance
      end

      break if new_center.id == center.id

      center = new_center

      jump_size /= 2
    end

    best
  end

  def first_after_id(id)
    select(:id, :created_at).where('id >= ?', id).order('id asc').first
  end
end

ActiveRecord::Base.send(:extend, FirstAfterCreatedAt)

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
first_after_created_at-0.0.1 lib/first_after_created_at.rb