Ruby:在使用if else with break时使用void值表达式

时间:2018-12-24 15:23:01

标签: ruby github pull-request

我是Ruby语言的新手。我正在整合Danger以便在GitHub PR上添加检查。用例之一是检查PR中的已修改文件是否包含特定更改。我在DangerFile中添加了以下代码

filesArray = ["Resources/Config.plist", "Resources/Deployment.plist"]

def modified_files_contains_change(files, change)
    does_contain_required_changes = false
    for file in files do
        message "diff in #{file}"
        diff = git.diff_for_file(file)
        patch_contains_change = diff.patch =~ #{change}
        if diff && patch_contains_change
            does_contain_required_changes = true
        else
            does_contain_required_changes = false
            break
        end
    end
    message "Does contain changes in all files => #{does_contain_required_changes}"
    does_contain_required_changes
end

if modified_files_contains_change(files, change)
   warn "Some useful warning message goes here"
end

在我的CI上运行此命令时,我遇到错误了

[!] Invalid `Dangerfile` file: void value expression. 

 #  from Dangerfile:33
 #  -------------------------------------------
 #              does_contain_required_changes = false
 >              break
 #          end
 #      end
 #  -------------------------------------------

我尝试搜索,但不了解出了什么问题。有人可以帮我了解确切的问题吗?预先感谢。

1 个答案:

答案 0 :(得分:1)

=~ #{change}被读为=~,因为#开始内联注释。 =~期望其中一侧具有正则表达式。要解决此问题,请更改以下行:

patch_contains_change = diff.patch =~ #{change}

收件人:

patch_contains_change = diff.patch =~ Regexp.new(change)

这假设您要以change的形式传递字符串。


此外,这将是或多或少红宝石的方式来完成任务:

def modified_files_contains_change(files, change)
  does_contain_required_changes =
    files.all? do |file|
      message "diff in #{file}"
      # break will immediately exit the `all?` unless diff is present
      break false unless diff = git.diff_for_file(file) 
      diff.patch =~ Regexp.new(change)
    end

  message "Does contain changes in all files => #{does_contain_required_changes}"
  does_contain_required_changes
end

要返回发现问题的文件,

def modified_files_contains_change(files, change)
  problematic_file =
    files.detect do |file|
      message "diff in #{file}"
      (diff = git.diff_for_file(file)).nil? || diff.patch !~ Regexp.new(change)
    end

  does_contain_required_changes = problematic_file.nil?
  if does_contain_required_changes
    message "All good!"
  else
    message "We have issues with file #{problematic_file}"
  end
  does_contain_required_changes
end