Class: Sequenced::Generator
- Inherits:
-
Object
- Object
- Sequenced::Generator
- Defined in:
- lib/sequenced/generator.rb
Instance Attribute Summary collapse
-
#column ⇒ Object
readonly
Returns the value of attribute column.
-
#record ⇒ Object
readonly
Returns the value of attribute record.
-
#scope ⇒ Object
readonly
Returns the value of attribute scope.
-
#skip ⇒ Object
readonly
Returns the value of attribute skip.
-
#start_at ⇒ Object
readonly
Returns the value of attribute start_at.
Instance Method Summary collapse
- #id_set? ⇒ Boolean
-
#initialize(record, options = {}) ⇒ Generator
constructor
A new instance of Generator.
- #next_id ⇒ Object
- #next_id_in_sequence ⇒ Object
- #set ⇒ Object
- #skip? ⇒ Boolean
- #unique?(id) ⇒ Boolean
Constructor Details
#initialize(record, options = {}) ⇒ Generator
Returns a new instance of Generator.
5 6 7 8 9 10 11 |
# File 'lib/sequenced/generator.rb', line 5 def initialize(record, = {}) @record = record @scope = [:scope] @column = [:column].to_sym @start_at = [:start_at] @skip = [:skip] end |
Instance Attribute Details
#column ⇒ Object (readonly)
Returns the value of attribute column.
3 4 5 |
# File 'lib/sequenced/generator.rb', line 3 def column @column end |
#record ⇒ Object (readonly)
Returns the value of attribute record.
3 4 5 |
# File 'lib/sequenced/generator.rb', line 3 def record @record end |
#scope ⇒ Object (readonly)
Returns the value of attribute scope.
3 4 5 |
# File 'lib/sequenced/generator.rb', line 3 def scope @scope end |
#skip ⇒ Object (readonly)
Returns the value of attribute skip.
3 4 5 |
# File 'lib/sequenced/generator.rb', line 3 def skip @skip end |
#start_at ⇒ Object (readonly)
Returns the value of attribute start_at.
3 4 5 |
# File 'lib/sequenced/generator.rb', line 3 def start_at @start_at end |
Instance Method Details
#id_set? ⇒ Boolean
19 20 21 |
# File 'lib/sequenced/generator.rb', line 19 def id_set? !record.send(column).nil? end |
#next_id ⇒ Object
27 28 29 30 31 |
# File 'lib/sequenced/generator.rb', line 27 def next_id next_id_in_sequence.tap do |id| id += 1 until unique?(id) end end |
#next_id_in_sequence ⇒ Object
33 34 35 36 37 38 39 40 |
# File 'lib/sequenced/generator.rb', line 33 def next_id_in_sequence start_at = self.start_at.respond_to?(:call) ? self.start_at.call(record) : self.start_at if (last_record = find_last_record) max(last_record.send(column) + 1, start_at) else start_at end end |
#set ⇒ Object
13 14 15 16 17 |
# File 'lib/sequenced/generator.rb', line 13 def set return if skip? || id_set? lock_table record.send(:"#{column}=", next_id) end |
#skip? ⇒ Boolean
23 24 25 |
# File 'lib/sequenced/generator.rb', line 23 def skip? skip&.call(record) end |
#unique?(id) ⇒ Boolean
42 43 44 45 46 47 48 |
# File 'lib/sequenced/generator.rb', line 42 def unique?(id) build_scope(*scope) do rel = base_relation rel = rel.where.not(record.class.primary_key => record.id) if record.persisted? rel.where(column => id) end.count == 0 end |