我已经阅读到ruby中的模块(在本例中为ActiveSupport :: Concern)在初始化的类的所有实例之间共享。因此,如果这是真的,则意味着任何实例变量都将在内存中的所有实例之间共享。
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'
以上代码安全使用吗?还是第二个用户会覆盖第一个用户?
答案 0 :(得分:2)
Module#include
被称为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.