Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/sequenced/acts_as_sequenced.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ module ClassMethods
# :skip - Skips the sequential ID generation when the lambda
# expression evaluates to nil. Gets passed the
# model object
# :secondary
# :column - Column for secondary index
# :value - lambda expression that you want to use to generate value for secondary index.
# Accepts two attributes: record and next_id
#
# Examples
#
Expand Down
10 changes: 9 additions & 1 deletion lib/sequenced/generator.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
module Sequenced
class Generator
attr_reader :record, :scope, :column, :start_at, :skip
attr_reader :record, :scope, :column, :start_at, :skip, :secondary_column, :secondary_value_generator

def initialize(record, options = {})
@record = record
@scope = options[:scope]
@column = options[:column].to_sym
@start_at = options[:start_at]
@skip = options[:skip]
@secondary_column = options.dig(:secondary, :column)
@secondary_value_generator = options.dig(:secondary, :value)
end

def set
return if skip? || id_set?
lock_table
record.send(:"#{column}=", next_id)
set_secondary_sequence(next_id)
end

def id_set?
Expand Down Expand Up @@ -79,5 +82,10 @@ def max(*values)
values.to_a.max
end

def set_secondary_sequence(next_id)
return if secondary_column.blank? || secondary_value_generator.blank?

record.send(:"#{secondary_column}=", secondary_value_generator.call(record, next_id))
end
end
end