Class: Sequential::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/sequential/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/sequential/generator.rb', line 5

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

Instance Attribute Details

#columnObject (readonly)

Returns the value of attribute column.



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

def column
  @column
end

#recordObject (readonly)

Returns the value of attribute record.



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

def record
  @record
end

#scopeObject (readonly)

Returns the value of attribute scope.



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

def scope
  @scope
end

#skipObject (readonly)

Returns the value of attribute skip.



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

def skip
  @skip
end

#start_atObject (readonly)

Returns the value of attribute start_at.



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

def start_at
  @start_at
end

Instance Method Details

#id_set?Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/sequential/generator.rb', line 35

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

#setObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/sequential/generator.rb', line 13

def set
  unless id_set? || skip?
    where_opts = {
      model:  record.class.name,
      column: column
    }

    where_opts.merge!(  scope: scope.to_s,
                        scope_value: record.send(scope.to_sym).to_s,
                     ) if scope

    sequence = Sequential::Sequence.where(where_opts).
                                      first_or_create(value: start_at - 1)

    sequence.with_lock do
      sequence.value += 1
      record.send(:"#{column}=", sequence.value)
      sequence.save
    end
  end
end

#skip?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/sequential/generator.rb', line 39

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