I have been tinkering with various ways to clean this up and I was wondering if it is more ideal to break this into small methods or way to accomplish this on a single line?
def run_counters
@num_attempts ||= 0
@num_attempts += retry_attempt
@all_attempts ||= 0
@all_attempts += retry_limit
end
-
\$\begingroup\$ Welcome to Code Review – your question has been migrated here. So that we may advise you properly, please add contextual information about what your code does, preferably a substantial part of the controller. Unlike Stack Overflow, which prefers short, abstract questions, Code Review needs full details. (See How to Ask.) \$\endgroup\$200_success– 200_success2016年09月01日 16:59:39 +00:00Commented Sep 1, 2016 at 16:59
1 Answer 1
Either initialize the variables in your class's constructor (that's specifically what it's for!) or define accessor methods to isolate the initialization logic for each variable:
# via constructor:
def initialize
@num_attempts = 0
@all_attempts = 0
end
def run_counters
num_attempts += retry_attempt
all_attempts += retry_limit
end
Or:
# via accessor methods:
def run_counters
num_attempts += retry_attempt
all_attempts += retry_limit
end
def num_attempts
@num_attempts ||= 0
end
def all_attempts
@all_attempts ||= 0
end
This also means you may safely access num_attempts
and all_attempts
from any other method, and not have to duplicate the initialization logic.
-
\$\begingroup\$
run_counters
can be split into 2 different methods IMO. \$\endgroup\$Arup Rakshit– Arup Rakshit2016年09月01日 17:07:32 +00:00Commented Sep 1, 2016 at 17:07