我真的被困在这部分了:
如果我禁用# 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
如果我在脚本中启用 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
我的脚本的几行:
# 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
我无法从全局配置文件中禁用 rubocop
,但如果它可以解决,我也会尝试这个:
Metrics/AbcSize:
Description: >-
A calculated magnitude based on number of assignments,
branches, and conditions.
Reference: 'http://c2.com/cgi/wiki?AbcMetric'
Enabled: true
最佳答案
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
此外,如果您需要禁用多个警察,您可以使用以下命令启用所有警察:
# rubocop:enable all
希望有帮助!
编辑:在查看 Tom Lord 对您的问题的评论后,我注意到您尚未发布违反警察规则的实际方法。不过,如果您将 disable
和 enable
语句放在正确的位置,我提供的解决方案应该可以工作。此外,我赞同 Tom 所说的,如果您向我们展示代码,我们可能会改进该方法,并且您不需要禁用该方法的警察。
关于ruby - # 鲁博科普 :disable Metrics/AbcSize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48100213/