Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top