Skip to content

Commit 7ab4d64

Browse files
committedFeb 24, 2015
Cleanup Module#attr_reader and Module#attr_writer
1 parent 5fdd6f7 commit 7ab4d64

File tree

1 file changed

+46
-23
lines changed

1 file changed

+46
-23
lines changed
 

Diff for: ‎opal/corelib/module.rb

+46-23
Original file line numberDiff line numberDiff line change
@@ -79,20 +79,33 @@ def attr_accessor(*names)
7979
attr_writer(*names)
8080
end
8181

82+
alias attr attr_accessor
83+
8284
def attr_reader(*names)
8385
%x{
84-
for (var i = 0, length = names.length; i < length; i++) {
85-
(function(name) {
86-
self.$$proto[name] = nil;
87-
var func = function() { return this[name] };
86+
var proto = self.$$proto;
8887
89-
if (self.$$is_singleton) {
90-
self.$$proto.constructor.prototype['$' + name] = func;
91-
}
92-
else {
93-
Opal.defn(self, '$' + name, func);
94-
}
95-
})(names[i]);
88+
for (var i = names.length - 1; i >= 0; i--) {
89+
var name = names[i],
90+
id = '$' + name;
91+
92+
// the closure here is needed because name will change at the next
93+
// cycle, I wish we could use let.
94+
var body = (function(name) {
95+
return function() {
96+
return this[name];
97+
};
98+
})(name);
99+
100+
// initialize the instance variable as nil
101+
proto[name] = nil;
102+
103+
if (self.$$is_singleton) {
104+
proto.constructor.prototype[id] = body;
105+
}
106+
else {
107+
Opal.defn(self, id, body);
108+
}
96109
}
97110
}
98111

@@ -101,25 +114,35 @@ def attr_reader(*names)
101114

102115
def attr_writer(*names)
103116
%x{
104-
for (var i = 0, length = names.length; i < length; i++) {
105-
(function(name) {
106-
self.$$proto[name] = nil;
107-
var func = function(value) { return this[name] = value; };
117+
var proto = self.$$proto;
108118
109-
if (self.$$is_singleton) {
110-
self.$$proto.constructor.prototype['$' + name + '='] = func;
111-
}
112-
else {
113-
Opal.defn(self, '$' + name + '=', func);
119+
for (var i = names.length - 1; i >= 0; i--) {
120+
var name = names[i],
121+
id = '$' + name + '=';
122+
123+
// the closure here is needed because name will change at the next
124+
// cycle, I wish we could use let.
125+
var body = (function(name){
126+
return function(value) {
127+
return this[name] = value;
114128
}
115-
})(names[i]);
129+
})(name);
130+
131+
// initialize the instance variable as nil
132+
proto[name] = nil;
133+
134+
if (self.$$is_singleton) {
135+
proto.constructor.prototype[id] = body;
136+
}
137+
else {
138+
Opal.defn(self, id, body);
139+
}
116140
}
117141
}
142+
118143
nil
119144
end
120145

121-
alias attr attr_accessor
122-
123146
def autoload(const, path)
124147
%x{
125148
var autoloaders;

0 commit comments

Comments
 (0)
Please sign in to comment.