Class: ClusterId::V1::Generator
- Inherits:
-
Object
- Object
- ClusterId::V1::Generator
- Defined in:
- lib/clusterid/v1/generator.rb
Overview
Create instances of Value objects based on time, random data, and serializable values for data centre, environment, and type IDs.
Instance Method Summary collapse
-
#from_byte_string(s) ⇒ Value
The Value represented by
s
. -
#generate(data_centre: nil, environment: nil, type_id: nil) ⇒ Value
Generate a Value for a given data centre, environment, and type ID.
-
#initialize(serializer: NullSerializer.new, deserializer: NullDeserializer.new, byte_generator: SecureRandom, clock: Clock) ⇒ Generator
constructor
A new instance of Generator.
Constructor Details
#initialize(serializer: NullSerializer.new, deserializer: NullDeserializer.new, byte_generator: SecureRandom, clock: Clock) ⇒ Generator
Note:
It is the caller's responsibility to ensure the serializer and deserializer follow the expected bit lengths for custom types. No overflow checks are done. Overflow will either be discarded or overwrite other bits. See the Value class for allowed bit lengths.
Returns a new instance of Generator.
19 20 21 22 23 24 |
# File 'lib/clusterid/v1/generator.rb', line 19 def initialize(serializer: NullSerializer.new, deserializer: NullDeserializer.new, byte_generator: SecureRandom, clock: Clock) @serializer = serializer @deserializer = deserializer @byte_generator = byte_generator @clock = clock end |
Instance Method Details
#from_byte_string(s) ⇒ Value
Returns the Value represented by s
.
51 52 53 |
# File 'lib/clusterid/v1/generator.rb', line 51 def from_byte_string(s) Value.new(s, @deserializer) end |
#generate(data_centre: nil, environment: nil, type_id: nil) ⇒ Value
Generate a Value for a given data centre, environment, and type ID.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/clusterid/v1/generator.rb', line 32 def generate(data_centre: nil, environment: nil, type_id: nil) raw_data = +"" # Nonce raw_data += @byte_generator.bytes(5) # Type ID raw_data += [@serializer.from_type_id(type_id)].pack("S") # Details (Version, Data Centre, Environment) raw_data += [ (FORMAT_VERSION << 5) + (@serializer.from_data_centre(data_centre) << 2) + @serializer.from_environment(environment) ].pack("C") # Timestamp raw_data += [@clock.now_ms].pack("Q") Value.new(raw_data.freeze, @deserializer) end |