ica*_*oli 4

不,这不对。快速浏览一下 cattr_reader 代码:

# File activesupport/lib/active_support/core_ext/class/attribute_accessors.rb, line 28
def cattr_reader(*syms)
  options = syms.extract_options!
  syms.each do |sym|
    class_eval(        unless defined? @@#{sym}          @@#{sym} = nil        end        def self.#{sym}          @@#{sym}        end, __FILE__, __LINE__ + 1)

    unless options[:instance_reader] == false
    class_eval(          def #{sym}            @@#{sym}          end, __FILE__, __LINE__ + 1)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

你可以运行简单的测试:

class A
  cattr_accessor :b
end

t1 = Thread.new { A.b = 1;  sleep 1; p (A.b == 1); }
t2 = Thread.new { A.b = 2 }
t1.join
t2.join
# outputs "false"
Run Code Online (Sandbox Code Playgroud)

这是一种使其线程安全地工作的方法:http://rails-bestpractices.com/posts/2010/08/23/fetch-current-user-in-models/