ActiveSupport::Concern 中的实例变量

Instance variables in ActiveSupport::Concern

我读到 ruby 中的模块(在本例中为 ActiveSupport::Concern)在 class 初始化的所有实例之间共享。因此,如果这是真的,则意味着任何实例变量都将在内存中的所有实例之间共享。

module SetPassword
  extend ActiveSupport::Concern
  attr_reader :password
  def password=(new_password)
    @password = new_password
    self.crypted_password = password_digest(new_password, salt)
  end
end

class User
  include SetPassword
end

u = User.new; u.password = 'abcdef'
u2 = User.new; u2.password = '123456'

上面的代码可以安全使用吗?或者第二个用户会覆盖第一个用户吗?

Module#include is under the hood calling Module#append_features。这意味着,没有任何内容 是共享的,这可能很容易检查(ActiveSupport::Concern 与您要检查的代码无关。)

module SetPassword
  attr_reader :password
  def password=(new_password)
    @password = new_password
    puts <<~EOS
    Setting password to: #{@password} (id: #{@password.__id__}).
    Object: #{self.class.name} (#{self.__id__}).
    Method: #{__callee__} on #{self.method(__callee__).__id__}.
    EOS
  end 
end

class User
  include SetPassword
end

u1 = User.new; u1.password = 'abcdef'
u2 = User.new; u2.password = '123456'

上面的代码演示了一切(密码本身、实例变量甚至它自己的方法)都是不同的:

▶ u1 = User.new; u1.password = 'abcdef'
#⇒ Setting password to: abcdef (id: 46968741459360).
#  Object: User (46968741459420).
#  Method: password= on 46968741459040.

▶ u2 = User.new; u2.password = '123456'
#⇒ Setting password to: 123456 (id: 46968734231740).
#  Object: User (46968734232020).
#  Method: password= on 46968734230640.