I have a Module A, and there are several Class need to Mixin it, there is a method should be wrote as Class Method of that Module, but this method need to get data from the Tables which match these Classes. It that realizable?
我有一个模块A,并且有几个类需要Mixin它,有一个方法应该写为该模块的类方法,但是这个方法需要从与这些类匹配的表中获取数据。那可以实现吗?
module Authenticate
def password=(password)
if password.present?
generate_salt
self.hashed_password = Authenticate.encrypt_password(password, salt)
end
end
class << self
def encrypt_password(password,salt)
Digest::SHA2.hexdigest(password + salt)
end
end
private
def generate_salt
self.salt = self.object_id.to_s + rand.to_s
end
end
require 'authenticate_module'
class Administrator < ActiveRecord::Base
validates :password, :confirmation => true
attr_accessor :password_confirmation
attr_reader :password
include Authenticate
end
This is that method:
这是方法:
def authenticate(name,password)
if user = ???.find_by_name(name)
if user.hashed_password == Authenticate.encrypt_password(password,user.salt)
user
end
end
end
1 个解决方案
#1
1
Use ActiveSupport::Concern to add class methods to every class that includes your module, then calling self in that method will return the class name.
使用ActiveSupport :: Concern将类方法添加到包含模块的每个类,然后在该方法中调用self将返回类名。
It will be something like:
它将是这样的:
module Authenticate
extend ActiveSupport::Concern
module ClassMethods
def authenticate(name, password)
self.class # returns the name of the class that includes this module
end
end
end
class User
include Authenticate
end
# Now You can call
User.authenticate(name, password)
What ActiveSupport::Concern does is that whenever a class includes the module, it extends that class with the ClassMethods which here is equivalent to doing
ActiveSupport :: Concern所做的是,每当一个类包含该模块时,它都会使用ClassMethods扩展该类,这里等同于
class User
include Authenticate
extend Authenticate::ClassMethods
end
#1
1
Use ActiveSupport::Concern to add class methods to every class that includes your module, then calling self in that method will return the class name.
使用ActiveSupport :: Concern将类方法添加到包含模块的每个类,然后在该方法中调用self将返回类名。
It will be something like:
它将是这样的:
module Authenticate
extend ActiveSupport::Concern
module ClassMethods
def authenticate(name, password)
self.class # returns the name of the class that includes this module
end
end
end
class User
include Authenticate
end
# Now You can call
User.authenticate(name, password)
What ActiveSupport::Concern does is that whenever a class includes the module, it extends that class with the ClassMethods which here is equivalent to doing
ActiveSupport :: Concern所做的是,每当一个类包含该模块时,它都会使用ClassMethods扩展该类,这里等同于
class User
include Authenticate
extend Authenticate::ClassMethods
end