What's the difference between these Ruby namespace conventions?

后端 未结 2 1376
庸人自扰
庸人自扰 2020-12-12 19:40

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

module SomeNamespace
  class Animal

  end
end

animal = Some         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 19:46

    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.

提交回复
热议问题