Feature #8275

Add Module#public_const_get

Added by Konstantin Haase about 1 year ago. Updated about 1 year ago.

[ruby-core:54332]
Status:Open
Priority:Normal
Assignee:-
Category:-
Target version:-

Description

Right now, const_get will always return a constant, no matter the visibility, which is probably what we want most of the time. But if you for instance have code that does some automatic name to constant resolution, you might now want to leak private constants.

module Foo
Bar = 42
private_constant :Bar
end

currently:

Foo::Bar # raises NameError
Foo.constget("Bar") # => 42
Object.const
get("Foo::Bar") # => 42

proposed:

Foo.publicconstget("Bar") # raises NameError
Object.publicconstget("Foo::Bar") # raises NameError

History

#1 Updated by Vipul Amler about 1 year ago

=begin

And vice-versa for set too maybe

(({Module#publicconstset}))/
(({Module#privateconstset}))

=end

#2 Updated by Charles Nutter about 1 year ago

What about an optional boolean for the existing constget/constset that indicates whether private constants should be included?

I guess having separate methods does align with publicinstancemethod and friends, though.

#3 Updated by Konstantin Haase about 1 year ago

I was considering a boolean. However, const_get already takes a boolean argument indicating whether or not to include inherited constants, and two boolean arguments would not make a readable API, I guess.

Maybe this would be a good use case for keyword arguments if the API were to be extended?

For instance with the following signature:

const_get(name, inherited = true, private: true)

Or even overload so that the old signature still works

const_get(name, inherited = true)

but it might also support

const_get(name, inherited: true, private: true)

What do you think?

#4 Updated by Charles Nutter about 1 year ago

rkh (Konstantin Haase) wrote:

I was considering a boolean. However, const_get already takes a boolean argument indicating whether or not to include inherited constants, and two boolean arguments would not make a readable API, I guess.

Ahh, good point. I agree.

Maybe this would be a good use case for keyword arguments if the API were to be extended?

For instance with the following signature:

const_get(name, inherited = true, private: true)

Or even overload so that the old signature still works

const_get(name, inherited = true)

but it might also support

const_get(name, inherited: true, private: true)

What do you think?

Interesting ideas. I'm starting to lean back toward having a separate method rather than pushing too much logic into this one. Keyword args definitely help readability if we wanted to overload, but maybe we really don't need to overload it more than it is overloaded already?

Also available in: Atom PDF