1

I've got some purely UI related computation like determining the html/css class in the following example:

<% class = score < 60 ? "red" : "green" %>

If this is done in the erb templates rather than the controller, which is preferred when creating the variable, class or @class?

1
  • It is usually discouraged to set variables in views. Views have one purpose, which is to present information to a user. So all the code in the view should be a template for what the user sees. This kind of decision should be made in a helper (as one answer suggested) so the view can hide the logic and just call that method. Commented Jun 2, 2020 at 7:44

2 Answers 2

1

which is preferred when creating the variable, class or @class?

You can't create a variable called class since is a reserved keyword. In the other hand @class is perfectly valid.

Speaking about creating variables in a view file, that's not good advice. It's often common to encourage people to leave views far from any logic you might have.

If you're in the rush of doing so, then simply use a ternary operator:

score < 60 ? 'red' : 'green'
Sign up to request clarification or add additional context in comments.

1 Comment

My bad for the random choice of example😂
1

If local variable is enough, use local variable.

But, apart from that, view is virtually never a good place to define any variables. Why don't you use helper instead? Like this, for example:

def score_class(score)
  score < 60 ? 'red' : 'green'
end

2 Comments

If the computed value will be used multiple times, is there a way to "cache" the value so that the helper method does not need to be called multiple times?
Look for "memoization" or low-level caching @wlnirvana.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.