Is there an acceptable way of putting multiple module declarations on the same line?
I am working on a code base that has many modules nested 4 or 5 deep. Right now, this results in our code being heavily indented from the beginning.
Is there an acceptable way of putting multiple开发者_如何学编程 module declarations on the same line?
For example,
module A
module B
#do stuff
end
end
Is there a way to make it something like this?
module A::B
#do stuff
end
Though the previous block doesn't work, I was able to get this next one to work, however I am not sure if this is considered acceptable code construction.
module A module B
#do stuff
end end
You can use ;
instead of \n
safely in Ruby source files. Newlines before end
are not important.
module A ; module B
#do stuff
end end
Or for example:
def sqr x ; x*x end
etc.
I think you've answered it yourself - your third segment looks pretty bad to my eye.
But, more to the point, if you did write module A::B
and module A
had never been defined before, you would be implicitly defining an (empty) module A
, which doesn't seem very useful. And, once you've defined module A
once, you're welcome to write module A::B
to define module B
. So it seems actively good to me that you can't use your second example.
Do this, though it's a bit naughty:
class Module
def const_missing(m)
const_set(m, Module.new)
end
end
module A::B
def self.hello_my_friend
:hello_my_friend
end
end
A::B.hello_my_friend #=> :hello_my_friend
Ruby doesn't use significant whitespace in the same way as Python does (though it can provide you with warnings if the indentation seems wonky), so you can simply not indent the code if you don't want to do so. It'd just make the code harder to read.
Incidentally, you may want to check whether four or five levels of modules indicates a code smell.
精彩评论