Skip to content

Commit 996a27e

Browse files
committed
let instance thread_mattr_* methods delegate to the class-level ones
This code has too much duplication and the rationale for the concatenation may not be obvious to the reader. You define the ones at class-level, explain why does the code concatenates there, and then the convenience ones at instance-level just delegate.
1 parent e9852c9 commit 996a27e

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,16 +39,19 @@ def thread_mattr_reader(*syms)
3939

4040
syms.each do |sym|
4141
raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym)
42+
43+
# The following generated method concatenates `name` because we want it
44+
# to work with inheritance via polymorphism.
4245
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
4346
def self.#{sym}
44-
Thread.current["attr_"+ name + "_#{sym}"]
47+
Thread.current["attr_" + name + "_#{sym}"]
4548
end
4649
EOS
4750

4851
unless options[:instance_reader] == false || options[:instance_accessor] == false
4952
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
5053
def #{sym}
51-
Thread.current["attr_"+ self.class.name + "_#{sym}"]
54+
self.class.#{sym}
5255
end
5356
EOS
5457
end
@@ -78,16 +81,19 @@ def thread_mattr_writer(*syms)
7881
options = syms.extract_options!
7982
syms.each do |sym|
8083
raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym)
84+
85+
# The following generated method concatenates `name` because we want it
86+
# to work with inheritance via polymorphism.
8187
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
8288
def self.#{sym}=(obj)
83-
Thread.current["attr_"+ name + "_#{sym}"] = obj
89+
Thread.current["attr_" + name + "_#{sym}"] = obj
8490
end
8591
EOS
8692

8793
unless options[:instance_writer] == false || options[:instance_accessor] == false
8894
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
8995
def #{sym}=(obj)
90-
Thread.current["attr_"+ self.class.name + "_#{sym}"] = obj
96+
self.class.#{sym} = obj
9197
end
9298
EOS
9399
end

0 commit comments

Comments
 (0)