Class: Unique::Generator

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

Constant Summary collapse

DEFAULT =
{
  start: 1,
  scoped_by: nil,
  formatter: nil
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attribute, opts = {}) ⇒ Generator

Returns a new instance of Generator.



11
12
13
14
# File 'lib/unique_id/generator.rb', line 11

def initialize(attribute, opts={})
  @attribute = attribute
  @opts = DEFAULT.merge(opts)
end

Instance Attribute Details

#attributeObject (readonly)

Returns the value of attribute attribute.



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

def attribute
  @attribute
end

Instance Method Details

#formatterObject



20
21
22
# File 'lib/unique_id/generator.rb', line 20

def formatter
  @opts[:formatter]
end

#next(opts) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/unique_id/generator.rb', line 24

def next(opts)
  _scope = opts[:scope].nil? ? nil : opts[:scope].to_s
  _type  = opts[:type]

  table = Arel::Table.new(:unique_ids)
  query = table
    .project( table[:value].maximum.as('v1') )
    .where( table[:type].eq(_type).and(table[:scope].eq(_scope)) )
  result = ActiveRecord::Base.connection.execute(query.to_sql).first
  max = result.is_a?(Hash) ? result['v1'] : result[0]

  next_value = max.nil? ? @opts[:start] : max.to_i + 1

  ins_query = table.create_insert
  ins_query.into table
  ins_query.insert table[:type]=>_type, table[:scope]=>_scope, table[:value]=>next_value
  result = ActiveRecord::Base.connection.insert(ins_query, nil, nil, next_value)
  raise "Unexpected result: #{result}" unless result == next_value

  next_value
end

#scopeObject



16
17
18
# File 'lib/unique_id/generator.rb', line 16

def scope
  @opts[:scoped_by]
end