我有这段代码,但我不喜欢那种不提 golint 的感觉,不喜欢 error should be the last type when return multiple items (golint) 。解释这段代码:
我愿意以任何方式重构它(将其分解、移动等)Go 中是否有更惯用的方式来完成这样的事情?
// Download will download the audio and video files to a particular path
func (r *RedditVideo) Download() (outputVideoFileName string, outputAudioFileName string, errVideo error, errAudio error) {
outputVideoFile, errVideo := downloadTemporaryFile(
r.VideoURL,
TemporaryVideoFilePrefix,
)
if errVideo == nil {
outputVideoFileName = outputVideoFile.Name()
}
outputAudioFile, errAudio := downloadTemporaryFile(
r.AudioURL,
TemporaryAudioFilePrefix,
)
if errAudio == nil {
outputAudioFileName = outputAudioFile.Name()
}
return outputVideoFileName, outputAudioFileName, errVideo, errAudio
}
类似地,我发现自己稍后在代码中再次使用了相同的模式:
// SetFiles sets up all of the input files and the output file
func (l *localVideo) SetFiles(inputVideoFilePath string, inputAudioFilePath string, outputVideoFilePath string) (errVideo error, errAudio error, errOutputVideo error) {
// Set input video file
l.inputVideoFile, errVideo = os.Open(inputVideoFilePath)
if errVideo != nil {
return
}
if errVideo = l.inputVideoFile.Close(); errVideo != nil {
return
}
// Set output video file
l.outputVideoFile, errOutputVideo = os.Create(outputVideoFilePath)
if errOutputVideo != nil {
return
}
if errOutputVideo = l.outputVideoFile.Close(); errOutputVideo != nil {
return
}
// IMPORTANT! Set input audio file LAST incase it is nil
l.inputAudioFile, errAudio = os.Open(inputAudioFilePath)
if errAudio != nil {
return
}
if errAudio = l.inputAudioFile.Close(); errVideo != nil {
return
}
return
}
这次在这段代码中,部分内容与上面相同:
最佳答案
您在标准库中可以看到很多特定函数,它们包装了更通用的非导出函数。请参阅下面的注释代码。
// download is a rather generic function
// and probably you can refactor downloadTemporaryFile
// so that even this function is not needed any more.
func (r *RedditVideo) download(prefix, url string) (filename string, error error) {
outputFile, err := downloadTemporaryFile(
r.VideoURL,
prefix,
)
if err == nil {
return "", fmt.Errorf("Error while download: %s", err)
}
return outputFile.Name(), nil
}
// DownloadVideo wraps download, handing over the values specific
// to the video download
func (r *RedditVideo) DownloadVideo() (filename string, averror error) {
return r.download(TemporaryVideoFilePrefix, r.VideoURL)
}
// DownloadAudio wraps download, handing over the values specific
// to the audio download
func (r *RedditVideo) DownloadAudio() (filename string, averror error) {
return r.download(TemporaryAudioFilePrefix, r.AudioURL)
}
func main() {
r := RedditVideo{
VideoURL: os.Args[1],
AudioURL: os.Args[2],
}
var videoerror, audioerror error
var videofileName, audiofileName string
if videofileName, videoerror = r.DownloadVideo(); videoerror != nil {
fmt.Println("Got an error downloading the video")
}
if audiofileName, audioerror = r.DownloadAudio(); audioerror != nil {
fmt.Println("Got an error downloading the audio")
}
fmt.Printf("Video:\t%s\nAudio:\t%s", videofileName, audiofileName)
}
这样一来,返回的错误来自于哪个下载就一目了然了。
关于go - 返回多个错误或相应地处理它们的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53858609/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何