module Vissen::Parameterized::Value
The Value
module implements the basic functionallity of a value type. Class implementations are encouraged to override write
to provide type checking or coercion.
Usage¶ ↑
The following example implements an integer type by calling to_i on objects before they are written.
class Int include Value DEFAULT = 0 def write(new_value) super new_value.to_i end end
Constants
- DEFAULT
@return [Object] the default value that will be used when `.new` is
called without arguments, or with nil.
Attributes
@return [Object] the internal value object.
Public Class Methods
Converts a class name to a string.
Vissen::Parameterized::Value::Real -> "real"
@param klass [Class] the class to canonicalize. @return [String] a string version of the class name.
# File lib/vissen/parameterized/value.rb, line 83 def self.canonicalize(klass) klass.name .split('::').last .gsub(/([a-z\d])([A-Z])/, '\1_\2') .downcase end
@param value [Object] the initial value to use. Ignored if nil.
# File lib/vissen/parameterized/value.rb, line 31 def initialize(value = nil) @value = nil @tainted = true write(value.nil? ? self.class::DEFAULT : value) end
@return [Array<Module>] an array of the modules and classes that include
the `Value` module.
# File lib/vissen/parameterized/value.rb, line 73 def self.types @types end
Private Class Methods
@param mod [Module]
# File lib/vissen/parameterized/value.rb, line 104 def self.included(mod) (@types ||= []) << mod end
Public Instance Methods
Values are always considered part of the global scope.
@return [Scope] the scope of the value.
# File lib/vissen/parameterized/value.rb, line 67 def scope GlobalScope.instance end
@return [true] if the value has been written to since the last call to
`#untaint!`.
@return [false] otherwise.
# File lib/vissen/parameterized/value.rb, line 53 def tainted? @tainted end
@return [String] the value formated as a string, with an appended '*' if
the value is tainted.
# File lib/vissen/parameterized/value.rb, line 92 def to_s base = @value.to_s tainted? ? base + '*' : base end
Marks the value as untainted.
@return [false]
# File lib/vissen/parameterized/value.rb, line 60 def untaint! @tainted = false end
Updates the internally stored value. The object will be marked as tainted if the new value differs from the previous.
@param new_value [Object] the new value to write. @return [true] if the value was changed. @return [false] otherwise.
# File lib/vissen/parameterized/value.rb, line 44 def write(new_value) return false if new_value == @value @value = new_value taint! end
Protected Instance Methods
# File lib/vissen/parameterized/value.rb, line 99 def taint! @tainted = true end