class AutoIncrement::Incrementor

AutoIncrement::Incrementor

Public Class Methods

new(column = nil, options = {}) click to toggle source
# File lib/auto_increment/incrementor.rb, line 5
def initialize(column = nil, options = {})
  if column.is_a? Hash
    options = column
    column = nil
  end

  @column = column || options[:column] || :code
  @options = options.reverse_merge initial: 1, force: false
  @options[:scope] = [@options[:scope]] unless @options[:scope].is_a? Array
  @options[:model_scope] = [@options[:model_scope]] unless @options[:model_scope].is_a? Array
end

Public Instance Methods

before_create(record) click to toggle source
# File lib/auto_increment/incrementor.rb, line 17
def before_create(record)
  @record = record
  write if can_write?
end
Also aliased as: before_validation, before_save
before_save(record)
Alias for: before_create
before_validation(record)
Alias for: before_create

Private Instance Methods

build_model_scope(query) click to toggle source
# File lib/auto_increment/incrementor.rb, line 45
def build_model_scope(query)
  @options[:model_scope].reject(&:nil?).each do |scope|
    query = query.send(scope)
  end

  query
end
build_scopes(query) click to toggle source
# File lib/auto_increment/incrementor.rb, line 35
def build_scopes(query)
  @options[:scope].each do |scope|
    if scope.present? && @record.respond_to?(scope)
      query = query.where(scope => @record.send(scope))
    end
  end

  query
end
can_write?() click to toggle source
# File lib/auto_increment/incrementor.rb, line 27
def can_write?
  @record.send(@column).blank? || @options[:force]
end
increment() click to toggle source
# File lib/auto_increment/incrementor.rb, line 70
def increment
  max = maximum

  max.blank? ? @options[:initial] : max.next
end
lock?() click to toggle source
# File lib/auto_increment/incrementor.rb, line 66
def lock?
  @options[:lock] == true
end
maximum() click to toggle source
# File lib/auto_increment/incrementor.rb, line 53
def maximum
  query = build_scopes(build_model_scope(@record.class))
  query.lock if lock?

  if string?
    query.select("#{@column} max")
         .order(Arel.sql("LENGTH(#{@column}) DESC, #{@column} DESC"))
         .first.try :max
  else
    query.maximum @column
  end
end
string?() click to toggle source
# File lib/auto_increment/incrementor.rb, line 76
def string?
  @options[:initial].class == String
end
write() click to toggle source
# File lib/auto_increment/incrementor.rb, line 31
def write
  @record.send :write_attribute, @column, increment
end