diff --git a/lib/keisan/context.rb b/lib/keisan/context.rb index 164c471..b7b6362 100644 --- a/lib/keisan/context.rb +++ b/lib/keisan/context.rb @@ -111,7 +111,11 @@ def register_function!(name, function, local: false) end def random - @random || @parent&.random || Random.new + @random ||= @parent&.random || Random.new + end + + def set_random(random) + @random = random end protected diff --git a/lib/keisan/version.rb b/lib/keisan/version.rb index 25776be..c6726a0 100644 --- a/lib/keisan/version.rb +++ b/lib/keisan/version.rb @@ -1,3 +1,3 @@ module Keisan - VERSION = "0.8.6" + VERSION = "0.8.7" end diff --git a/spec/keisan/context_spec.rb b/spec/keisan/context_spec.rb index 311d3c1..f5ef08d 100644 --- a/spec/keisan/context_spec.rb +++ b/spec/keisan/context_spec.rb @@ -166,6 +166,25 @@ expect(matches.any? {|bool| bool == false}).to be true end + + it "has the random object set once and only once" do + context = described_class.new + random = context.random + expect(random).to eq context.random + end + + it "can be set to override existing internal random object" do + rand1 = Random.new(2244) + rand1_copy = Random.new(2244) + rand2 = Random.new(4466) + + context = described_class.new(random: rand2) + context.set_random(rand1_copy) + + 20.times do + expect(context.random.rand(100)).to eq rand1.rand(100) + end + end end describe "has_variable?" do diff --git a/spec/version_spec.rb b/spec/version_spec.rb index 0f1dd24..fcee67a 100644 --- a/spec/version_spec.rb +++ b/spec/version_spec.rb @@ -2,6 +2,6 @@ RSpec.describe Keisan do it "has the expected version number" do - expect(Keisan::VERSION).to eq "0.8.6" + expect(Keisan::VERSION).to eq "0.8.7" end end