Search code examples
ruby-on-railsrubydynamicdevisepasswords

Ruby on Rails Devise Gem Set minimum password length dynamically


Currently I am setting the password length with

config.password_length = 6..128

but how can I change it dynamically during runtime without restarting the server?

I implemented

def password_complexity

I could check it in there but then I have to disable the setting in config. How can I disable it?


Solution

  • The Validatable module just generates a bunch of Rails validations for you https://github.com/heartcombo/devise/blob/367ea427626ea8d9a8315b296535a4d93f311fab/lib/devise/models/validatable.rb#L37

    Since :within doesnt take a symbol or a lambda it seems you either have to do some ugly meta programming to remove the validation rule and replace it with your own or you could just not include the Devise :validatable module and set all the validation rules yourself for more fine grained control

    class User < ApplicationRecord
      validates_length_of :password, minimum: -> (user) { user.password_range.first }, maximum: -> (user) { user.password_range.last }, allow_blank: true
      # other password/email rules
    
      private
      
      def password_range
        if something?
          (12..250)
        else
          (4..20)
        end
      end
    end