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)