# rubocop:禁用 Metrics/AbcSize

dev*_*der 2 ruby chef-infra rubocop

我真的被困在这部分:

如果我禁用# rubocop:disable Metrics/AbcSize,那么我会收到此错误:

ruby -v : ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin14]

rubocop -V
0.52.1 (using Parser 2.4.0.2, running on ruby 2.4.2 x86_64-darwin14)


$ rubocop .
Inspecting 7 files
.....W.

Offenses:

recipes/default.rb:13:1: W: Lint/MissingCopEnableDirective: Re-enable Metrics/AbcSize cop with # rubocop:enable after disabling it.
# rubocop:disable Metrics/AbcSize
^

7 files inspected, 1 offense detected
Run Code Online (Sandbox Code Playgroud)

如果我rubocop在脚本中启用然后得到:

rubocop .
Inspecting 7 files
.....C.

Offenses:

recipes/default.rb:31:1: C: Metrics/AbcSize: Assignment Branch Condition size for check_tropo_versions is too high. [33.02/20]
def check_tropo_versions ...
^^^^^^^^^^^^^^^^^^^^^^^^

7 files inspected, 1 offense detected
Run Code Online (Sandbox Code Playgroud)

我的脚本的几行:

# rubocop:enable Metrics/AbcSize

require 'nokogiri'
Chef.event_handler do
  on :resource_updated do |resource, _action|
    if resource.declared_type.to_s == 'remote_file' && resource.cookbook_name == 'tropo-patch' && resource.recipe_name == 'default'
      puts "#{Time.now.strftime('%Y%m%d%H%M%S')},#{resource.path},#{resource.source[0]}"
      File.open('/var/log/tropo-patch.log', 'a') { |f| f.write("#{Time.now.strftime('%Y%m%d%H%M%S')},#{resource.path},#{resource.source[0]}\n") }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我无法从全局配置文件中禁用rubocop,但如果它可以解决我也会尝试这个:

Metrics/AbcSize:
  Description: >-
                 A calculated magnitude based on number of assignments,
                 branches, and conditions.
  Reference: 'http://c2.com/cgi/wiki?AbcMetric'
  Enabled: true
Run Code Online (Sandbox Code Playgroud)

Ili*_*mov 6

Rubocop 基本上抱怨的是,它要求您在方法关闭后启用 cop,以便 cop 可以对文件的其他方法有效。如果在文件的第一行禁用它,则该文件中的所有方法都将禁用它。对整个文件禁用警察并不是一个好主意,因为在禁用警察时您应该明确且有意识。

您的情况的修复方法只是在您的方法之前禁用警察,然后在之后启用它。

例如:

# rubocop:disable Metrics/AbcSize

require 'nokogiri'
Chef.event_handler do
  on :resource_updated do |resource, _action|
    if resource.declared_type.to_s == 'remote_file' && resource.cookbook_name == 'tropo-patch' && resource.recipe_name == 'default'
      puts "#{Time.now.strftime('%Y%m%d%H%M%S')},#{resource.path},#{resource.source[0]}"
      File.open('/var/log/tropo-patch.log', 'a') { |f| f.write("#{Time.now.strftime('%Y%m%d%H%M%S')},#{resource.path},#{resource.source[0]}\n") }
    end
  end
end

# rubocop:enable Metrics/AbcSize
Run Code Online (Sandbox Code Playgroud)

此外,如果您需要禁用多个警察,您可以使用以下命令启用所有警察:

# rubocop:enable all
Run Code Online (Sandbox Code Playgroud)

希望有帮助!

编辑:在查看汤姆·洛德对你的问题的评论后,我注意到你还没有发布违反警察规则的实际方法。disable不过,如果您将和enable语句放在正确的位置,我提供的解决方案应该有效。此外,我同意 Tom 所说的,如果您向我们展示代码,我们可能会改进该方法,并且您不需要禁用该方法的警察。