-
Notifications
You must be signed in to change notification settings - Fork 0
/
Prototypal.rb
86 lines (70 loc) · 1.36 KB
/
Prototypal.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class Prototypal
def initialize(prototype)
@proto = prototype
@props = Hash.new
end
def create_object
Prototypal.new(self)
end
def proto
@proto
end
def method_missing(method_sym, *arguments, &block)
delegate(self, method_sym, arguments)
end
def delegate(instance, method_sym, arguments)
ok, value = try_set(method_sym, arguments)
if ok
return value
end
ok, value = try_get(method_sym, arguments)
if ok
return instance.maybe_call(value, arguments)
end
if @proto
@proto.delegate(instance, method_sym, arguments)
else
Undefined.value
end
end
def respond_to?(method_sym, include_private = false)
true
end
def maybe_call(value, arguments)
if value.respond_to?(:call)
instance_exec(*arguments, &value)
else
value
end
end
private
def is_setter(method_sym)
s = method_sym.inspect
s.start_with?(":") && s.end_with?("=")
end
def try_set(method_sym, *arguments)
if is_setter(method_sym) && arguments.length == 1
s = method_sym.inspect
key = s[1, s.length - 2]
@props[key] = arguments[0][0]
[true, arguments[0]]
else
[false, nil]
end
end
def try_get(method_sym, arguments)
s = method_sym.inspect
key = s[1, s.length - 1]
if @props.has_key?(key)
[true, @props[key]]
else
[false, nil]
end
end
end
class Undefined
@@value = Undefined.new
def self.value
@@value
end
end