call a class method from inside an instance method from a module mixin (rails)
Posted
by sean
on Stack Overflow
See other posts from Stack Overflow
or by sean
Published on 2010-03-25T18:20:14Z
Indexed on
2010/03/25
18:23 UTC
Read the original article
Hit count: 633
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?
© Stack Overflow or respective owner