开发者

What is the effect of creating a folder, is it an automatic namespace?

I have a two part question.

Question 1.

I've always thought a folder was an automatic namespace, but I just went back and refactored some code and ended up with something like this:

  • a folder named formatter
  • a file formatter.rb that contained references to all of the files within the fol开发者_JAVA百科der
  • a formatter/formatter.rb file that has a class Formatter, with no reference to the namespace
  • 3 other classes that inherit from class Formatter: FooFormatter, BarFormatter, BazFormatter, with no reference to the namespace
  • one ActionFormatter class that does not inherit from class Formatter, and has no reference to the namespace

What surprised me was that I didn't need to create namespaces around each of the file like I have in the past. Like:

Module Formatter
  Class ActionFormatter

Is this because the Module Formatter is implied by being in this folder? I still have to reference it as Formatter::ActionFormatter when it is called. But why doesn't FooFormatter need this reference.

Question 2.

Everything seems to work, but I get this warning:

warning: toplevel constant FormatAction referenced by Formatter::FormatAction on the line where I have

@formatter = Formatter::ActionFormatter

Why is this?


No, a folder does not define a namespace all by itself. The rails autoloading mechanism though, tries to load the definition for a non existint constant A::B::C within a/b/c.rb. If you define another constant there (especially without a namespace), it will exist (without namespace). If there is both, a toplevel constant and a namespaced constant with the same name and you access this constant from within the namespace, you get the above warning.

When you go with rails, you have to define namespaced constants with their namespace, like this: class A::B::C < D. Also, as far as I know, inheritance does not influence namespacing in any way.


@moritz is correct, just a little addition for future searchers.

GOTCHAS

Can't load namespaced controllers

Errors:

warning: toplevel constant Finance referenced by Member::Finance

OR

uninitialized constant Finance

Cause:

a namespaced controller / helper which is listed BEFORE it's dependency. e.g. ll member/finance/ bank_batches_controller.rb base_controller.rb

Fix:

make this the first line of the dependent:

require_dependency "#{RAILS_ROOT}/app/controllers/member/finance/base_controller"

Requiring the dependent file before attempting to load the class. (Yes, this goes before class ...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜