Module: FirstAfterCreatedAt

Defined in:
lib/first_after_created_at.rb,
lib/first_after_created_at/version.rb

Constant Summary collapse

VERSION =
"1.1.0"

Instance Method Summary collapse

Instance Method Details

#first_after_created_at(time) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/first_after_created_at.rb', line 2

def first_after_created_at(time)
  time = Time.parse(time.to_s)
  best = nil
  first = select(:id, :created_at).first
  return unless first
  min_id = first.id
  max_id = select(:id, :created_at).last.id

  loop do
    mid_id = (min_id + max_id) / 2
    mid_obj =
      select(:id, :created_at).where("#{quoted_table_name}.#{connection.quote_column_name('id')} >= ?", mid_id).order(:id).first

    best = get_best(mid_obj, time, best)
    break if min_id == max_id

    if mid_obj.created_at < time
      # handle even / odd
      min_id = mid_id < max_id ? mid_id + 1 : mid_id
    else
      max_id = mid_id > min_id ? mid_id - 1 : mid_id
    end
  end

  find(best.id) if best
end

#get_best(obj, time, best) ⇒ Object



29
30
31
32
33
# File 'lib/first_after_created_at.rb', line 29

def get_best(obj, time, best)
  return best if obj.created_at < time
  return obj if best.nil?
  obj.id < best.id ? obj : best
end