views:

203

answers:

1

Curious how one would go about calling a class method from inside an instance method of a module which is included by an active record class. For example I want both user and client models to share the nuts and bolts of password encryption.

# app/models
class User < ActiveRecord::Base
  include Encrypt
end
class Client < ActiveRecord::Base
  include Encrypt
end

# app/models/shared/encrypt.rb
module Encrypt
  def authenticate
    # I want to call the ClassMethods#encrypt_password method when @user.authenticate is run 
    self.password_crypted == self.encrypt_password(self.password) 
  end
  def self.included(base)
    base.extend ClassMethods
  end  
  module ClassMethods
    def encrypt_password(password)
     Digest::SHA1.hexdigest(password)
    end
  end
end  

However, this fails. Says that the class method cannot be found when the instance method calls it. I can call User.encrypt_password('password') but User.authenticate('password') fails to look up the method User#encrypt_password

Any thoughts?

A: 

You need the encrypt_password like a class method

module Encrypt
  def authenticate
    # I want to call the ClassMethods#encrypt_password method when @user.authenticate is run 
    self.password_crypted == self.class.encrypt_password(self.password) 
  end
  def self.included(base)
    base.extend ClassMethods
  end  
  module ClassMethods
    def encrypt_password(password)
     Digest::SHA1.hexdigest(password)
    end
  end
end 
shingara