I'm currently writing a script and I decided to run cane over it to look for some issues, and the following method was highlighted. I've done my best to cut it back, and at this point I'm inclined to leave it as-is, however cane is still giving it a pretty high rating of 23 (15 is the point it starts complaining) so I wanted to get some more input. Other than perhaps splitting fetching and generating does anyone have any ideas?
def self.generate(template, output_file, company)
puts 'Fetching data...'
@data = Provider::GenericProvider.create_provider(company['type'].to_sym, company).data
valid_keys = @data.keys.sort {|a,b| -(a <=> b)}[0,10]
@data = @data.select {|k, _| valid_keys.include? k}
valid_keys = @data.keys.sort {|a,b| -(a <=> b)}[0,2]
loop do
break if :done == choose {|menu| timesheet_menu valid_keys, menu}
end
puts 'Generating output...'
# Used as a result of the ERB binding
#noinspection RubyUnusedLocalVariable
data = @data.select {|k, _| valid_keys.include? k}
File.write(output_file, ERB.new(File.read(template), nil, '-').result(binding))
end
EDIT:
Since people are still replying, here is the current actual state of play (Note I've removed the intermediate steps now since this post was getting a bit long and dry. Feel free to check the edit history for previous steps this code has taken):
def process_template(template)
# snip...
feedback 'Fetching data...'
data = fetch_data(@config[company.to_s])
@data = select_data(data)
feedback 'Generating output...'
generate(template, output, @config[company.to_s], @data)
end
def fetch_data(company)
provider = Provider::GenericProvider.create_provider(company['type'].to_sym, company)
# False positive
#noinspection RubyHashKeysTypesInspection
Hash[provider.data.sort_by {|key, _| key }.last(10).reverse]
end
def select_data(data)
options = data.keys
chosen = options.first(2)
# #timesheet_menu will display a CUI menu to the user to select options from
until @highline.choose{|menu| timesheet_menu options, chosen, menu} == :done
end
data.select {|k, _| chosen.include? k}
end
# Locals are available to ERB and used in the templates
#noinspection RubyUnusedLocalVariable
def generate(template, output_file, company, data)
File.write(output_file, ERB.new(File.read(template), nil, '-').result(binding))
end
private
def timesheet_menu(options, chosen, menu)
menu.prompt = 'Please select which timesheets to use:'
options.sort { |a, b| -(a <=> b) }.each do |k|
menu.choice(k + (chosen.include?(k) ? ' (*)' : '')) do
if chosen.include? k
chosen.delete k
else
chosen.push k
end
end
end
menu.choice(:done)
end