evanphx (owner)

Revisions

gist: 193752 Download_button fork
public
Public Clone URL: git://gist.github.com/193752.git
Embed All Files: show embed
Text #
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class Attributes
  def initialize(parent)
    @parent = parent
    @children = []
    @values = {}
    @origins = {}
 
    parent.add_child(self) if parent
  end
 
  def add_child(child)
    @children << child
  end
 
  def get(key)
    if @values.key?(key)
      return @values[key]
    end
 
    origin, value = @parent.find(key)
    if value
      @values[key] = value
      @origins[key] = origin
      return value
    end
 
    # not found in any parent
    return nil
  end
 
  def find(key)
    if @values.key?(key) and !@origins[key]
      return self, @values[key]
    end
 
    if @parent
      @parent.find(key)
    else
      nil
    end
  end
 
  def set(key, val)
    @values[key] = val
    @origins[key] = nil
 
    @children.each { |c| c.set_inherited(key, val, self) }
  end
 
  def set_inherited(key, val, who)
    # ignore requests to set values we set on ourselves
    return if @origins.key?(key) and !@origins[key]
 
    @values[key] = val
    @origins[key] = who
 
    @children.each { |c| c.set_inherited(key, val, who) }
  end
end
 
class Cave
  def self.inherited(obj)
    obj.setup_attributes(self)
  end
 
  def self.setup_attributes(parent)
    @attributes = Attributes.new(parent.attributes)
  end
 
  def self.attributes
    @attributes ||= Attributes.new(nil)
  end
 
  def self.kind
    attributes.get :kind
  end
 
  def self.set_kind(which)
    attributes.set :kind, which
  end
end
 
Cave.set_kind "beach side"
p Cave.kind # beach side
 
class Sub1 < Cave
end
 
# == parent push values to children that inherited values
 
p Sub1.kind # beach side
Cave.set_kind "mountain"
p Cave.kind # mountain
p Sub1.kind # mountain
 
 
# == child sets it's own value
 
Sub1.set_kind "underwater"
p Sub1.kind # underwater
 
# == parent sets don't flow into children with own values
 
Cave.set_kind "mountain top"
p Cave.kind # mountain top
p Sub1.kind # underwater
 
# == multiple depth children
 
class Sub2 < Cave
end
 
p Sub2.kind # mountain top
 
class Sub3 < Sub2
end
 
p Sub3.kind # mountain top
 
# == set on influences subclasses only
 
Sub2.set_kind "moon"
 
p Sub2.kind # moon
p Sub3.kind # moon
 
Cave.set_kind "desert"
 
p Sub2.kind # moon
p Sub3.kind # moon
 
Sub2.set_kind "martian"
 
p Sub3.kind # martian