5
\$\begingroup\$

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  endend
Jamal's user avatar
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
askedOct 9, 2012 at 22:22
Douglas Birch's user avatar
\$\endgroup\$

2 Answers2

3
\$\begingroup\$

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

attr_accessor :submitted_passwordvalidate :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  endend

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 explicitreturn (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.

answeredOct 10, 2012 at 9:05
tokland's user avatar
\$\endgroup\$
3
  • \$\begingroup\$Thank you for the explanation and example - much appreciated!\$\endgroup\$CommentedOct 10, 2012 at 15:03
  • \$\begingroup\$This returnsnil when the password is valid.\$\endgroup\$CommentedNov 10, 2012 at 21:09
  • \$\begingroup\$@steenslag: Indeed, I tried to write the method as a Rails callback, but the code was incomplete. Edited.\$\endgroup\$CommentedNov 10, 2012 at 21:42
0
\$\begingroup\$

There is no need to write explicitreturn . You can omit it. Because in Ruby the result of last executed statement in your code is returned automatically.

answeredOct 10, 2012 at 3:18
Prathamesh Sonpatki's user avatar
\$\endgroup\$
1
  • \$\begingroup\$Care to expand your answer a bit to explainwhyreturn can be omitted?\$\endgroup\$CommentedOct 10, 2012 at 4:30

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.