Get constants
We looked at ways of inspecting methods by opening up their object forms and peeking into classes.
It is often used to instantiate classes at runtime, like creating an object of a class for a particular user input. If you're familiar with Rails, then you might have seen this used for instantiating controllers depending on a certain URL being requested. As class names are constants too, it is really easy to do that.
Because this is just working with strings that are assumed to be constant names, it would not work if your classes aren't named constants.
This also restricts the scope for the constant search to the class
const_get
allows us another form of inspection, not entirely unlike eval
; using constant names as a String
or a Symbol
.
const_get
is defined on Module
, but it works for classes as well, as Class
is a subclass of Module
. It returns a NameError
if the value of that constant isn't found. This is the only way you can access nested constants, as const_get
only parses properly formed named constants and does not parse colons like Monk::ZEN
.
Monk
. If it doesn't find the constant in that scope it goes up the ancestral chain and starts looking from Object
.
eval
isn't exactly safe. Modify the Editor
exercise from the last lesson to use const_get
instead of eval
to parse the name of the class in the second filter.