-
Notifications
You must be signed in to change notification settings - Fork 0
/
delayed_constraint.rb
42 lines (35 loc) · 994 Bytes
/
delayed_constraint.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Object
@@constraints = {}
def self.constraint(name, definition)
@@constraints[name] = definition
end
def constraint(name, definition)
self.class.constraint(name, definition)
end
alias_method :_always, :always
def always(constraint_name, bindings, context)
DelayedConstraint.new(@@constraints[constraint_name.to_sym]).bind(bindings, context, :_always)
end
def once(constraint_name, bindings, context)
DelayedConstraint.new(@@constraints[constraint_name.to_sym]).bind(bindings, context, :_once)
end
def _once(*args, &block)
constraint = _always(*args, &block)
constraint.disable
constraint
end
end
class DelayedConstraint
attr_reader :constraint
def initialize(constraint_definition)
@constraint = constraint_definition
end
def bind(bindings, context, type)
unless bindings.nil?
bindings.each do |key, value|
@constraint = constraint.gsub(":#{key.to_s}", value.to_s)
end
end
eval("#{type} #{constraint}", context)
end
end