I want to turn these three methods into one, but am unable to wrap my brain around it at this moment. Complicated by the fact that 1/3 requires a slightly different call. They’re all similar enough, and I know there is a better way, but beyond my skill level right now. With one extra variable passed in (fetch, check, or process) I could turn it into one, how to do this eludes me.
If you were to refactor these into one method, how would you do it?
def fetch(subjects = current_subjects, queues = QUEUES)
subjects.each do |s|
queues.each { |x| fetch_results(x, s) } unless queue.nil?
end
end
def check(subjects = current_subjects, queues = QUEUES)
subjects.each do |s|
queues.each { |x| check_results(s["#{x}_recent"]) } unless queue.nil?
end
end
def process(subjects = current_subjects, queues = QUEUES)
subjects.each do |s|
queues.each { |x| process_results(s["#{x}_recent"]) } unless queue.nil?
end
end
EDIT: One solution is close to what I was thinking earlier, but I didn’t make it clear that I want to pass in the what as a smallish array, that might be expandable and can used to indicate whether to fetch, check, or process or any combination of those. So, essentially, I’m trying to loop through three things with one method:
- an action what: I.E., fetch, check, or process.
- any number of subjects.
- any number of queues, which is a constant at the moment.
Also, other solutions here:
@Lucapette proposes a top-down solution (which I think it’s pretty valid on most cases). However, @Tony correctly points out that methods may evolve and so it may be too rigid. The alternative solution is a bottom-up approach:
Ditto for the other methods. BTW, that double
eachcan also be written: