Module: Mongokit::Counter

Defined in:
lib/mongokit/auto_increment/counter.rb

Class Method Summary collapse

Class Method Details

.next(options) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/mongokit/auto_increment/counter.rb', line 5

def next(options)
  record = Models::AutoIncrementCounter.where({
    counter_model_name: options[:model].collection_name,
    counter_field: options[:attribute]
  }).find_and_modify({ '$inc' => { counter: options[:step] }}, new: true)

  return record.counter if options[:pattern].nil?

  if outdated?(record, options[:time_format])
    record.set(counter: options[:start] + options[:step])
  end

  Formater.new.format(record.counter, options)
end

.outdated?(record, time_format) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/mongokit/auto_increment/counter.rb', line 20

def outdated?(record, time_format)
  Time.now.strftime(time_format).to_i > record.updated_at.strftime(time_format).to_i
end

.to_time_format(pattern) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/mongokit/auto_increment/counter.rb', line 24

def to_time_format(pattern)
  event = String.new

  event += '%Y' if pattern.include? '%y' or pattern.include? '%Y'
  event += '%m' if pattern.include? '%m'
  event += '%H' if pattern.include? '%H'
  event += '%M' if pattern.include? '%M'
  event += '%d' if pattern.include? '%d'
  event
end