Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

What's the difference between these Ruby namespace conventions?

So Module can be used in Ruby to provide namespacing in addition to mixins, as so:

module SomeNamespace
  class Animal

  end
end

animal = SomeNamespace::Animal.new

But I've also seen the following used:

module SomeNamespace
end

class SomeNamespace::Animal

end

animal = SomeNamespace::Animal.new

My question is how they're different (if they are) and which is more idiomatic Ruby?

question from:https://stackoverflow.com/questions/7821459/whats-the-difference-between-these-ruby-namespace-conventions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The difference lies in nesting.

In the example below, you can see that the former method using class Foo, can get the outer scope's constant variables BAR_A without errors.

Meanwhile, class Baz will bomb with an error of uninitialized constant A::B::Baz::BAR_A. As it doesn't bring in A::* implicitly, only A::B::*explicitly.

module A
  BAR_A = 'Bar A!'
  module B
    BAR_B = 'Bar B!'
      class Foo
        p BAR_A
        p BAR_B
      end
  end
end

class A::B::Baz
  p BAR_A
  p BAR_B
end

Both behaviors have their place. There's no real consensus in the community in my opinion as to which is the One True Ruby Way (tm). I personally use the former, most of the time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...