class Rubactive::TimeVaryingValue
A TimeVaryingValue
represents a value that might “mysteriously” change each time you look at it.
The current value can change in three ways:
-
Explicitly, via change_to. That’s no different than setting an attribute of any sort of object.
-
It might have been created to “follow” other time-varying values. In that case, it will react to any of their changes by recalculating itself (in a way defined when it was created.)
-
It might have been created to follow a
DiscreteValueStream
. In that case, any value added to the stream becomes the time-varying value’s current value.
There is a different constructor for each of the above cases. In addition, variables can be implicity created by sending unrecognized messages to other time-varying values.
origin = TimeVaryingValue.starting_with(5) follower = origin + 1 follower.current #=> 6 origin.change_to(700) follower.current #=> 701
Public Class Methods
Create a value that changes as the values it depends upon change.
When any followed variables change, the block is called with their current values. The result becomes the current value for this TimeVaryingValue
.
Example:
verb = TimeVaryingValue.starting_with("vote") adverb = TimeVaryingValue.starting_with("early") tracker = TimeVaryingValue.follows(verb, adverb) { | v, a | "#{v} #{a}!" } tracker.current #=> "vote early!" adverb.change_to("often") tracker.current #=> "vote often!"
If no block is given, this value should be following only one other. It adopts that other value whenever it changes.
# File lib/rubactive/rubactive.rb, line 139 def self.follows(*values, &block) super end
Create a new TimeVaryingValue
.
Since the returned instance follows nothing, only change_to
can be used to change its value.
# File lib/rubactive/rubactive.rb, line 147 def self.starting_with(initial_value) follows { initial_value } end
Create a time-varying value that follows the latest value in a stream.
The first argument must be a DiscreteValueStream
. Whenever that stream has a new value added, the time-varying value changes to match.
The time-varying value always starts with the given initial_value, even if stream has previously had some values added to it.
# File lib/rubactive/rubactive.rb, line 160 def self.tracks_stream(value_stream, initial_value) retval = follows(value_stream) retval.change_to(initial_value) retval end
Public Instance Methods
Change the current value.
# File lib/rubactive/rubactive.rb, line 172 def change_to(new_value); self.value=new_value; end
Retrieve the current value.
Earlier values are inaccessible.
# File lib/rubactive/rubactive.rb, line 169 def current; value; end