HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrubyMinor

Validating a password format

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
formatvalidatingpassword

Problem

How should I make this more Ruby-like or just "better"?

def password_format_is_valid?(submitted_password)

  #Gets regular expression for password format validation from settings and applies it
  regex = Regexp.new(Setting['global_admin.password_format_regex'])
  if submitted_password =~ regex then
    return true
  else
    self.errors.add(:password, Setting['global_admin.password_format_error_message'])
    return false
  end

end

Solution

It seems like you need a Rails validation callback (and a virtual attribute for submitted_password). I'd write:

attr_accessor :submitted_password
validate :password_format_is_valid?

def password_format_is_valid?
  regex = Regexp.new(Setting['global_admin.password_format_regex'])
  unless submitted_password =~ regex
    self.errors.add(:password, Setting['global_admin.password_format_error_message'])
    false
  end
end


Comments:

-
In the vein of Lisp, the last expression of a body in Ruby is the return value of the method/block, so no need to use an explicit return (in fact it's unidiomatic and discouraged)

-
Note that Rails can validate fields with regular expression, you should use the predefined validations whenever possible: validates_format_of.

Code Snippets

attr_accessor :submitted_password
validate :password_format_is_valid?

def password_format_is_valid?
  regex = Regexp.new(Setting['global_admin.password_format_regex'])
  unless submitted_password =~ regex
    self.errors.add(:password, Setting['global_admin.password_format_error_message'])
    false
  end
end

Context

StackExchange Code Review Q#16378, answer score: 3

Revisions (0)

No revisions yet.