constraint / 0.2
| Short description: | Ensure that objects always satisfy a set of constraints | |||||
|---|---|---|---|---|---|---|
| Category: | Library/Datastructure | |||||
| Status: | experimental | |||||
| Created: | 2005-06-10 17:33:46 GMT | |||||
| Last update: | 2005-06-15 07:42:54 GMT | |||||
| Owner: | tlink (Projects of this owner) | |||||
| Homepage: | http://constraint.rubyforge.org/ | |||||
| Download: | http://rubyforge.org/frs/?group_id=748 | |||||
| License: | GPL | |||||
| Dependency: |
|
|||||
| Description: | DescriptionThis library provides a way to ensure that certain objects always satisfy a specified set of constraints. An object that can be constrained must be a child of Constraint::Shell, which acts as a wrapper for the actual value. Constraints can added to subclasses and its instances (per-object constraints). It is possible to define methods that handle constraint violations and retrofit the object according to its definition. The primary use of this library is to define "typed"/constrained arrays that may only contain certain elements that meet a set of requirements, e.g., non-nil, kind of some class, a certain attribute set … With some help from the developer, this library can also be used (to some extent at least) to generate correct values and to find solutions fitting the set of constraints.
class EvenInteger < Constraint::Shell
and_constraint("Numeric") {|o, e| e.kind_of?(Integer)}
and_constraint("Even") {|o, e| e.modulo(2) == 0}
end
enum = EvenInteger.new(2)
enum.and_constraint("LT10") {|o, e| e < 10}
p enum + 2
=> 4
p enum + 1
=> Fixnum didn't meet constraint 'Even': 3 (ConstraintViolation)
or:
class NumInRange < Constraint::Shell
constraint_attr :min, 0
constraint_attr :max, nil
and_constraint('Numeric') {|o, e| e.kind_of?(Numeric)}
and_constraint('InRange') {|o, e| o.min <= e && (!o.max || o.max >= e)}
on_constraint_violation('InRange') {|o, e| (o.max && e > o.max) ? o.max : o.min}
def generate_constrained_value(value)
if value
if !max or @max > value
value + 1
else
raise Constraint::NoMoreValues
end
else
@min
end
end
end
class Num1To10 < NumInRange
@min = 1
@max = 10
end
p Num1To10.new(5.2) + 2.2
=> 7.4
p Num1To10.new(5.2) + 20.2
=> 10
p Num1To10.new(5).collect_constrained_values
=> [5, 6, 7, 8, 9, 10]
Changes
|
|||||
| Versions: | [0.2 (2005-06-15)] [0.1 (2005-06-10)] | |||||