我有以下文件 lib/a/b/c.rb
class a::b::c
def request(env)
#some code here
end
end
现在我正在使用 rubocop 风格
Style/ClassAndModuleChildren:
Enabled: true
我为此受到了 rubocop 的攻击
lib/a/b/c.rb:1:7: C: Use nested module/class definitions instead of compact style.
class a::b::c
当我更新我的代码以修复以下问题时
样式一
class a
class b
class c
def request(env)
#some code here
end
end
end
end
样式 2
module a
module b
class c
def request(env)
#some code here
end
end
end
end
我认为我应该使用 Style 2
,因为我在我的一个文件中使用了 require 'a'
。
请让我知道如何解决这种类型和错误及其原因
最佳答案
这被标记为冒犯的原因是常量解析在 ruby 中是按词法工作的,而不是按语义工作的。这不直观,可能会导致一些模糊的错误(例如,如果您在两个不同的范围内有两个同名的类)。比较这两种情况:
# Given
module Foo
X = 42
end
# This
module Foo
class Bar
def baz
puts X
end
end
end
# VS
class Foo::Bar
def baz
puts X
end
end
现在当你打电话时:
Foo::Bar.new.baz
在第一种情况下你会得到 42
,在第二种情况下 - NameError: uninitialized constant Foo::Bar::X
至于哪个是正确的修复方法:请注意,如果
Foo
尚不存在,使用短语法会给您一个错误。答案是——你应该使用 Foo
是什么。如果它是一个类 - 使用 class
,如果它是一个模块 - module
。
关于ruby - 如何修复 a::b::c 类的 rubocop 攻击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34649576/