在Module Class方法中,是否可以获得那个模块中混合的类?

时间:2012-03-16 15:44:22

标签: ruby-on-rails ruby ruby-on-rails-3

我有一个模块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

这是方法:

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 个答案:

答案 0 :(得分:1)

使用ActiveSupport :: Concern将类方法添加到包含模块的每个类,然后在该方法中调用self将返回类名。

这将是:

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)

ActiveSupport :: Concern所做的是,只要一个类包含该模块,它就会使用ClassMethods扩展该类,这里等同于做

class User
  include Authenticate
  extend Authenticate::ClassMethods
end