Home > Net >  Uninitialized constant error when include a module
Uninitialized constant error when include a module

Time:11-26

Happened on ruby 3.1.2 & rails 7.0.4

module: app/models/concerns/password_regeneratable.rb

module PasswordRegeneratable
  extend ActiveSupport::Concern

  module ClassMethods
    def generate_password
      SecureRandom.urlsafe_base64(self.class::DEFAULT_PASSWORD_LENGTH)
    end
  end
end

model: app/models/user.rb

class User < ApplicationRecord
  include PasswordRegeneratable

  DEFAULT_PASSWORD_LENGTH = 30
end

When I try to call User.generate_password it gives me this error:

/app/app/models/concerns/password_regeneratable.rb:6:in `generate_password': uninitialized constant Class::DEFAULT_PASSWORD_LENGTH (NameError)
Did you mean?  Class::DEFAULT_SETTINGS

I want to use module so I can reuse this generate_password method and possible some other methods for other model classes in the future. Is this kind of implementation correct?

CodePudding user response:

module PasswordRegeneratable
  extend ActiveSupport::Concern

  module ClassMethods
    def generate_password
      SecureRandom.urlsafe_base64(self::DEFAULT_PASSWORD_LENGTH)
    end
  end
end

In a class method self is the class. Thus self.class gives you the confusingly named Class class since in Ruby classes are instances of Class.

  • Related