Class: GlobalUid::Allocator

Inherits:
Object
  • Object
show all
Defined in:
lib/global_uid/allocator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(incrementing_by:, connection:, table_name:) ⇒ Allocator

Returns a new instance of Allocator.



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

def initialize(incrementing_by:, connection:, table_name:)
  @recent_allocations = []
  @max_window_size = 5
  @incrementing_by = incrementing_by
  @connection = connection
  @table_name = table_name
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



3
4
5
# File 'lib/global_uid/allocator.rb', line 3

def connection
  @connection
end

#incrementing_byObject (readonly)

Returns the value of attribute incrementing_by.



3
4
5
# File 'lib/global_uid/allocator.rb', line 3

def incrementing_by
  @incrementing_by
end

#max_window_sizeObject (readonly)

Returns the value of attribute max_window_size.



3
4
5
# File 'lib/global_uid/allocator.rb', line 3

def max_window_size
  @max_window_size
end

#recent_allocationsObject (readonly)

Returns the value of attribute recent_allocations.



3
4
5
# File 'lib/global_uid/allocator.rb', line 3

def recent_allocations
  @recent_allocations
end

#table_nameObject (readonly)

Returns the value of attribute table_name.



3
4
5
# File 'lib/global_uid/allocator.rb', line 3

def table_name
  @table_name
end

Instance Method Details

#allocate_many(count:) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/global_uid/allocator.rb', line 18

def allocate_many(count:)
  return [] unless count > 0

  increment_by = connection.select_value("SELECT @@auto_increment_increment")

  start_id = connection.insert("REPLACE INTO #{table_name} (stub) VALUES " + (["('a')"] * count).join(','))
  identifiers = start_id.step(start_id + (count - 1) * increment_by, increment_by).to_a
  identifiers.each { |identifier| allocate(identifier) }
  identifiers
end

#allocate_oneObject



13
14
15
16
# File 'lib/global_uid/allocator.rb', line 13

def allocate_one
  identifier = connection.insert("REPLACE INTO #{table_name} (stub) VALUES ('a')")
  allocate(identifier)
end