Topic: Deep If Clauses

Hi, I find that I am writing a lot of deep IF clauses (on average 4 nested IFs) in my controllers, and that I have long chains of IF clauses in my views.  For example, some view code might look like this:

<% If logged_in? and own_blog? and comments_exist? etc... %>
  <%= display some stuff %>
<% end %>

Occasionally I put the IF chains in a private method to clean things up (or more accurately put the dirty stuff out of view).  Is there a better strategy to deal with long chains of requirements in controllers and views?

Thank you!,

Re: Deep If Clauses

I think that's a good opportunity to use helpers. In this example you could create a broader helper method like can_post? and use your other methods within it to clean up your views. For example:

def can_post?
if logged_in? and own_blog? and comments_exist?
#return true

If these methods extend across your entire app, you might want to even put it in your application controller.

Re: Deep If Clauses

By the way, use the "and" operator with care. It has a different precedence than the "&&" operator and its application may lead to unexpected results (the same goes to the "or" operator).

For example, the "and" operator has a lower precedence then the "=" operator. The following code:

result = first_condition and second_condition

is being evaluated like if it were written like this:
(result = first_condition) and second_condition

It's a little bit tricky, so be careful.