问题
If I have a list of items, and for every one of them I'm calling an instance method, how can I save the value of the method and prevent it from being calculated every time it's called?
Say I have two items:
<% if method_true %>
do something
<% end %>
<% if method_true %>
do something else
<% end %>
If method_true == true, how can I just pass the value true
through the two ifs instead of calculating it every time?
回答1:
I'm sure there's a more sophisticated answer out there, but for my app I just saved the value in an instance variable.
model
def method_true
#...
end
view
<% if @model.method_true.true? %>
<% @x = true %>
<% end %>
After that, you can use
<% if @x == true %>
instead of
<% if @model.method_true.true? %>
and the method won't have to recalculated. And if method_true
isn't true, than @x
will be nil, so the if?
conditionals won't be executed.
回答2:
You could memoize method_true?
(Ruby methods that return booleans end in question marks, by convention).
If your expensive calculation
can only be true/false:
def method_true?
if @method_true.nil?
@method_true = # your expensive calculation
end
@method_true
end
If you also care about memoizing nil:
def method_true?
unless defined?(@method_true)
@method_true = # your expensive calculation
end
@method_true
end
StackOverflow question on memoizing true/false/nil
来源:https://stackoverflow.com/questions/28613335/how-can-i-save-the-value-of-an-instance-method