Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I refactor this in Rails?

if formatted_address.blank? || country.blank? || lat.blank? || lng.blank?

If I have 10 attributes to check if blank, I don't wanna retype .blank? 10 times.

share|improve this question

closed as off-topic by Jamal Apr 24 '15 at 6:34

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

From the maintainability standpoint, multiple ORs or || are the same and you should opt to list them all. Just come up with the proper formatting - in this case if your underlying objects changes in structure, you can quickly update the condition. At the same time you may want to have all these conditions compiled into an aggregate field within the parent entity (the one that has "formatted_address" properties) but I dont see a big point in it based on the context. – Arthur P Oct 10 '12 at 15:49
@Arthur, thanks. – Victor Oct 10 '12 at 15:55
up vote 6 down vote accepted

You could do this. You still have a list of attributes, in case you need to change them later

if [formatted_address, country, lat, lng].any? { |field| field.blank? }
  # ...

Edit: By the way, the above can be shortened to:

if [formatted_address, country, lat, lng].any?(&:blank?)
  # ...
share|improve this answer

You can use or instead of ||. In Ruby or and and are used for control flow. So

(expr1) or (expr2)

If expr1 is false then expr2 will be evaluated. This is similar to failsafe condition. In your case, all if conditions can be combined using or

formatted_address.blank? or country.blank? or lat.blank? or lng.blank?

With this, all conditions will be checked but if any one of them is true, we want to execute some code. That can be achieved by using and

formatted_address.blank? or country.blank? or lat.blank? or lng.blank? and do_something

If your do_something is small enough this approach is useful.

More information about or and and in Ruby is here

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.