Class: Rooibos::Command::Random

Inherits:
Object
  • Object
show all
Includes:
Custom
Defined in:
lib/rooibos/command/random.rb

Overview

A command that generates a random value.

Games roll dice. Encryption needs keys. Shuffling needs seeds. All of these call Kernel#rand or Random. But randomness in Update is a side effect: the same model and message would produce different results on each call. Testing would become fragile and non-deterministic.

This command delegates to Ruby’s Random class through the runtime. Update receives the result as a Message::Random.

Use it for dice rolls, shuffles, key generation, or any feature that needs random values without side effects in Update.

Prefer the Command.random factory method for convenience.

Example: Dice roll

def update(msg, model)
  case msg
  in { type: :random, envelope: :roll, value: }
    model.with(die_face: value)
  end
end

Example: Random float

def update(msg, model)
  case msg
  in { type: :random, envelope: :spawn_chance, value: }
    model.with(should_spawn: value < 0.3)
  end
end

Instance Method Summary collapse

Methods included from Custom

#deconstruct_keys, #rooibos_cancellation_grace_period, #rooibos_command?

Instance Method Details

#call(out, token) ⇒ Object

Executes the random command.

Without a leading symbol, calls Random.rand with the stored arguments. With a leading symbol, calls that method on Random via public_send.

out

Outlet for sending messages.

token

Cancellation token from the runtime.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/rooibos/command/random.rb', line 55

def call(out, token)
  if token.canceled?
    out.put(Message::Canceled.new(command: self))
    return
  end

  value = if args.first.is_a?(Symbol)
    method_name = args.first
    ::Random.public_send(method_name, *args[1..])
  else
    ::Random.rand(*args)
  end
  out.put(Ractor.make_shareable(Message::Random.new(envelope:, value:)))
end