Sha256: baf81ec397f01a45b0d93c5d41ef9c2510f21d615bcad4a7f2491490c6ab4332
Contents?: true
Size: 1.41 KB
Versions: 2
Compression:
Stored size: 1.41 KB
Contents
# +AutoIncrement+ module AutoIncrement # +AutoIncrement::Incrementor+ class Incrementor def initialize(column = nil, options = {}) if column.is_a? Hash options = column column = nil end @column = column || options[:column] || :code @options = options.reverse_merge scope: nil, initial: 1, force: false @options[:scope] = [@options[:scope]] unless @options[:scope].is_a? Array end def before_create(record) @record = record write if can_write? end private def can_write? @record.send(@column).blank? || @options[:force] end def write @record.send :write_attribute, @column, increment end 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 def maximum query = build_scopes @record.class query.lock if lock? if string? query.select("#{@column} max") .order("LENGTH(#{@column}) DESC, #{@column} DESC") .first.try :max else query.maximum @column end end def lock? @options[:lock] == true end def increment max = maximum max.blank? ? @options[:initial] : max.next end def string? @options[:initial].class == String end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
auto_increment-1.3.0 | lib/auto_increment/incrementor.rb |
auto_increment-1.2.0 | lib/auto_increment/incrementor.rb |