Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Module.private_constant do? Is there a way to list only private constants?

Starting in Ruby 1.9.3, we can create private constants:

module M
  class C; end
  private_constant :C
end

Is there a good documentation about what this does? Is there a way to get the names of only private constants similar to calling constants

like image 980
sawa Avatar asked Oct 17 '12 22:10

sawa


2 Answers

There is no such thing as private constants until Ruby 1.9.3. To get a list of all the constants though, you can simply use constants.

module Mod
  CONST = "value"
end

Mod.constants #=> [:CONST]

From 1.9.3, private_constant was added, but as nothing is really private, you can do...

module Mod
  CONST = "value"
  private_constant :CONST
end

Mod.const_get(:CONST) #=> "value"

I don't think there is a way of getting a list of all the private constants but you can still test the presence of a particular name.

Mod.const_defined?(:CONST) #=> true
like image 163
tomferon Avatar answered Oct 14 '22 07:10

tomferon


As of Ruby 2.1, while Module#constants includes only public constants, if you set inherit=false, you will get private constants as well. So if you find a constant in constants(false) but not in constants (and you don't care about inherited constants), that might be a more or less reliable way to tell if it's private.

class Module
  def private_constants
    constants(false) - constants
  end
end

module Foo
  X = 1
  Y = 2
  private_constant :Y
end

puts "Foo.constants = #{Foo.constants}"
puts "Foo.constants(false) = #{Foo.constants(false)}"
puts "Foo.private_constants = #{Foo.private_constants}"

# => Foo.constants = [:X]
# => Foo.constants(false) = [:X, :Y]
# => Foo.private_constants = [:Y]

This is undocumented, and I'm not sure if it's intentional, but empirically it works. I would back it up with unit tests.


Update: It looks like this is a bug in Ruby, and may disappear in a future version.

like image 25
David Moles Avatar answered Oct 14 '22 06:10

David Moles