call a class method from inside an instance method from a module mixin (rails)
- by sean
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.new.encrypt_password fails
Any thoughts?