<分区>
我发现自己与深层命名空间(>= 深度为 4)作斗争,即使它们在逻辑上是有意义的,以避免它们引起的一些烦恼。
首先,我希望我的代码能够很好地适应文本编辑器窗口,而不必太宽。尽管 2 sp 的 ruby 常规缩进肯定有帮助,但这促使我使用范围运算符来避免所有嵌套缩进。但另一方面,使用范围运算符会带来一系列问题......
首先,要在当前命名空间上下文的上游某处使用常量,您必须使用该常量的完整命名空间,以便 Ruby 找到它。而且由于当我使用范围运算符时,命名空间深度很深,因此引用常量和类会变得很长。
require 'a/b'
class A::B::C
FOO = 'hi'
end
class A::B::C::D
# FOO # can't do this. raises NameError: uninitialized constant; would work fine if classes used nested format, but then the extra indent makes for wide code.
A::B::C::FOO # must use full reference when using scopes, ugh. Depending on the real names of A,B,C, this could be rather long as well.
end
其次,我遇到了一种情况,我必须在我的类定义之后要求文件,我不想这样做(我喜欢顶部的要求语句),就像这样。
# File: a/b/c.rb
require 'a/b'
# require 'a/b/c/d' # can't put it here, otherwise you get uninitialize const A::B::C when a/b/c/d.rb is getting interpreted.
class A::B::C
def initialize
@d = A::B::C::D.new
end
end
require 'a/b/c/d' # it bothers me putting requires anywhere but at the top
# File: a/b/c/d.rb
require 'a/b/c'
class A::B::C::D
end
必须付出一些东西。也许我只是需要让步并扩大我的编辑器并坚持使用嵌套,或者我可能不了解如何最好地使用范围运算符在命名空间的上下文中工作。
有没有人对我应该如何处理管理这些问题的深度命名空间有任何建议? 1. 通过最小化缩进来降低代码宽度 2. 当在当前上下文的上游定义常量时,能够仅使用常量名称 (FOO) 来引用常量 3. 将所有的require语句放在源代码文件的顶部