Class: AttrSequence::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/attr_sequence/generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(record, options = {}) ⇒ Generator

Returns a new instance of Generator.



5
6
7
8
9
10
11
# File 'lib/attr_sequence/generator.rb', line 5

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

Instance Attribute Details

#columnObject (readonly)

Returns the value of attribute column.



3
4
5
# File 'lib/attr_sequence/generator.rb', line 3

def column
  @column
end

#recordObject (readonly)

Returns the value of attribute record.



3
4
5
# File 'lib/attr_sequence/generator.rb', line 3

def record
  @record
end

#scopeObject (readonly)

Returns the value of attribute scope.



3
4
5
# File 'lib/attr_sequence/generator.rb', line 3

def scope
  @scope
end

#skipObject (readonly)

Returns the value of attribute skip.



3
4
5
# File 'lib/attr_sequence/generator.rb', line 3

def skip
  @skip
end

#start_atObject (readonly)

Returns the value of attribute start_at.



3
4
5
# File 'lib/attr_sequence/generator.rb', line 3

def start_at
  @start_at
end

Instance Method Details

#next_numberObject



27
28
29
30
31
# File 'lib/attr_sequence/generator.rb', line 27

def next_number
  next_number_in_sequence.tap do |number|
    number += 1 until unique?(number)
  end
end

#next_number_in_sequenceObject



33
34
35
36
37
# File 'lib/attr_sequence/generator.rb', line 33

def next_number_in_sequence
  start_at = self.start_at.respond_to?(:call) ? self.start_at.call(record) : self.start_at
  return start_at unless last_record = find_last_record
  max(last_record.send(column) + 1, start_at)
end

#number_set?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/attr_sequence/generator.rb', line 19

def number_set?
  !record.send(column).nil?
end

#setObject



13
14
15
16
17
# File 'lib/attr_sequence/generator.rb', line 13

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

#skip?Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/attr_sequence/generator.rb', line 23

def skip?
  skip && skip.call(record)
end

#unique?(number) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
43
44
45
# File 'lib/attr_sequence/generator.rb', line 39

def unique?(number)
  build_scope(*scope) do
    rel = base_relation
    rel = rel.where("NOT number = ?", record.number) if record.persisted?
    rel.where(column => number)
  end.count == 0
end