What's the differences btw const_get and qualified_const_get?

邮差的信 提交于 2019-12-22 09:28:33

问题


There is a series of methods, i.e., const_defined?, const_get, or const_set, in standard ruby library.

const_defined?, const_get, const_set

And also, in the Active Support Core Extensions of Rails, their "qualified_" counterparts for these individuals exist.

qualified_const_defined?, qualified_const_get, qualifeid_const_set

Is there anybody who can explain explicitly the differences between bare and qualified forms for these methods?

Thank you in advance.

Hyo


回答1:


The qualified_ const helpers support interacting with constants at arbitrary depths (not just children of the subject).

I think an example is the easiest way to explain this one. Let's say Foo::Bar::Baz exists:

 > Object::const_get "Foo::Bar::Baz"
NameError: wrong constant name Foo::Bar::Baz
 > Object::const_get "Foo"
=> Foo
 > Foo.const_get "Bar"
=> Foo::Bar
 > Foo::Bar.const_get "Baz"
=> Foo::Bar::Baz

The qualified_ methods allow you to avoid walking the module hierarchy directly:

 > Object::qualified_const_get "Foo::Bar::Baz"
=> Foo::Bar::Baz
 > Foo.qualified_const_set "Bar::Fizz", 123
=> 123
 > Foo::Bar::Fizz
=> 123

I'd recommend poking around the source, too. It's pretty clean.




回答2:


you might find this interesting:

http://redcorundum.blogspot.com/2006/05/kernelqualifiedconstget.html



来源:https://stackoverflow.com/questions/16071168/whats-the-differences-btw-const-get-and-qualified-const-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!