我需要重构以下rails函数,Rubocop不太喜欢复杂性,我正在尝试使用“ net / sftp”库上传文件
def record_answer(event, uploader, *args)
case event
when :open then
Rails.logger.info "starting upload: #{args[0].local} -> #{args[0].remote} (#{args[0].size} bytes} #{uploader}"
when :put then
Rails.logger.info "writing #{args[2].length} bytes to #{args[0].remote} starting at #{args[1]} #{uploader}"
when :close then
Rails.logger.info "finished with #{args[0].remote} #{uploader}"
when :mkdir then
Rails.logger.info "creating directory #{args[0]} #{uploader}"
when :finish then
Rails.logger.info 'all done!'
end
end
我试图用散列来解决它,但是不确定参数
答案 0 :(得分:1)
在Ruby中,所有内容都是一个表达式-甚至case语句和if / else构造,它们都返回一个值。
def record_answer(event, uploader, *args)
Rails.logger.info case event
when :open
"starting upload: #{args[0].local} -> #{args[0].remote} (#{args[0].size} bytes} #{uploader}"
when :put
"writing #{args[2].length} bytes to #{args[0].remote} starting at #{args[1]} #{uploader}"
when :close
"finished with #{args[0].remote} #{uploader}"
when :mkdir
"creating directory #{args[0]} #{uploader}"
when :finish
'all done!'
end
end
这使您只需使用表达式的返回值调用Rails.logger.info
即可。
另外,args[0].remote
和args[0].size
可以通过使用keyword arguments而不是将哈希作为位置参数传递来解决。
def record_answer(event, uploader, *args, remote: nil, size: nil, local: nil, **options)
Rails.logger.info case event
when :open
"starting upload: #{local} -> #{remote} (#{size} bytes} #{uploader}"
when :put
"writing #{args[2].length} bytes to #{remote} starting at #{args[1]} #{uploader}"
when :close
"finished with #{remote} #{uploader}"
when :mkdir
"creating directory #{args[0]} #{uploader}"
when :finish
'all done!'
end
end
答案 1 :(得分:0)
很抱歉我发布了一个可怕的问题,问题是Rubocop要求重构,因为它太复杂了,我找到了解决方法
我创建一个处理程序类
df.stack(level=1)
Out[483]:
c1st 1 2
id1st id2nd c2nd
bar one a 0.041343 -0.454746
b -0.711644 -0.644445
two a -0.752158 -1.889375
b -1.577000 -0.287645
baz one a 1.684986 -2.735571
b 1.143991 0.393892
two a -0.423235 -0.024267
b -0.136017 -0.998609
foo one a 0.618897 0.693133
b -1.153296 0.772482
two a 1.356303 -0.804281
b 0.624918 0.679210
qux one a 1.722674 -0.030559
b -0.406572 -0.446558
two a -1.025345 0.773167
b -0.207286 0.012901
然后我在上载函数中将其称为'net / sftp'支持的参数
class SFTPEventHandler
def on_open(uploader, file)
Rails.logger.info "starting upload: #{file.local} -> #{file.remote} (#{file.size} bytes) #{uploader}"
end
def on_put(uploader, file, offset, data)
Rails.logger.info "writing #{data.length} bytes to #{file.remote} starting at #{offset} #{uploader}"
end
def on_close(uploader, file)
Rails.logger.info "finished with #{file.remote} #{uploader}"
end
def on_mkdir(uploader, path)
Rails.logger.info "creating directory #{path} #{uploader}"
end
def on_finish(uploader)
Rails.logger.info "all done! #{uploader}"
end
end