I have a controller comparing parsed documents with databases of key words. Typical snippets are encapsulated loops looping through the parsed document, the database of key words counting the number a match and building an array of matching words. Here is an example :
@key_words = KeyWords.all
@count = 0
@array_of_matching_words = []
@parsed_document.each do |a|
@key_words.each do |word|
if a =~ /#{key_word.word}/
@count = @count+1
@array_of_matching_words = @array_of_matching_words.push "#{key_word.word}"
end
end
Both instantiated variable @count and @array_of_matching_words are passed to a view. I have accumulated numerous of those snippets for the other databases of words and I am trying to re-factor the code by moving some of this code into separate methods.
One of the option I have considered is to move the code to a private method in the controller
def get_the_number_and_the_list_of_matching_words
@key_words = KeyWords.all
@count = 0
@array_of_matching_words = []
@parsed_document.each do |a|
@key_words.each do |word|
if a =~ /#{key_word.word}/
@count = @count+1
@array_of_matching_words = @array_of_matching_words.push "#{key_word.word}"
end
end
end
I then just leave
get_the_number_and_the_list_of_matching_words
in my action controller and the view will get both @count and @array_of_matching_words.
I find this coding "style" terrible. The method "get_the_number_and_the_list_of_matching_words" appears out of the blue, it does not instantiate anything, no parameter is passed, both instantiated variable (@count, @array_of_matching_words) are not visible (they are burried at the bottom of my .rb file in the private methods section). Is this really a good way to re-factor the code or is there other option? Does it make sense to move code to a method when the method is neither an instance method nor a method requiring to pass a parameter and returning new variables?