How do I refactor this in Rails?
if formatted_address.blank? || country.blank? || lat.blank? || lng.blank?
...
end
If I have 10 attributes to check if blank, I don't wanna retype .blank? 10 times.
Thanks.
|
How do I refactor this in Rails?
If I have 10 attributes to check if blank, I don't wanna retype Thanks. |
||||
|
You could do this. You still have a list of attributes, in case you need to change them later
Edit: By the way, the above can be shortened to:
|
||||
|
|
|
You can use or instead of ||. In Ruby or and and are used for control flow. So
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
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
If your do_something is small enough this approach is useful. More information about or and and in Ruby is here |
|||
|
|
.blank?10 times. – Victor Oct 10 '12 at 15:43