Class: Vident::StableId

Inherits:
Object
  • Object
show all
Defined in:
lib/vident/stable_id.rb

Defined Under Namespace

Classes: GeneratorNotSetError, StrategyNotConfiguredError

Constant Summary collapse

RANDOM_FALLBACK =
->(generator) do
  return Random.hex(16) unless generator
  generator.next.join("-")
end
STRICT =
->(generator) do
  unless generator
    raise GeneratorNotSetError,
      "No Vident::StableId sequence generator is set on the current thread. " \
      "Call Vident::StableId.set_current_sequence_generator(seed: ...) in a " \
      "before_action (or wrap the render in StableId.with_sequence_generator)."
  end
  generator.next.join("-")
end

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.strategyObject

Callable(generator_or_nil) -> String. Starts nil; host app must configure it.



29
30
31
# File 'lib/vident/stable_id.rb', line 29

def strategy
  @strategy
end

Class Method Details

.clear_current_sequence_generatorObject



35
36
37
# File 'lib/vident/stable_id.rb', line 35

def clear_current_sequence_generator
  ::Thread.current[:vident_number_sequence_generator] = nil
end

.next_id_in_sequenceObject



47
48
49
50
51
52
53
54
55
# File 'lib/vident/stable_id.rb', line 47

def next_id_in_sequence
  unless @strategy
    raise StrategyNotConfiguredError,
      "Vident::StableId.strategy is not configured. Run " \
      "`bin/rails generate vident:install`, or set it manually in an " \
      "initializer (e.g. `Vident::StableId.strategy = Vident::StableId::STRICT`)."
  end
  @strategy.call(::Thread.current[:vident_number_sequence_generator])
end

.set_current_sequence_generator(seed:) ⇒ Object



31
32
33
# File 'lib/vident/stable_id.rb', line 31

def set_current_sequence_generator(seed:)
  ::Thread.current[:vident_number_sequence_generator] = id_sequence_generator(seed)
end

.with_sequence_generator(seed:) ⇒ Object



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

def with_sequence_generator(seed:)
  previous = ::Thread.current[:vident_number_sequence_generator]
  set_current_sequence_generator(seed: seed)
  yield
ensure
  ::Thread.current[:vident_number_sequence_generator] = previous
end