Josué Lima
Josué Lima

Reputation: 483

Access a private constant from module

Is there any way to access a private constant from an included module?

This is what I would like to do:

module B
  def access_private_here
    puts MY_CONST
  end
end

class A
  include B
  private
    MY_CONST = 1
end

I know that if this constant was public I could do self.class::MY_CONST, is there any way to the same with a private cons?

Upvotes: 5

Views: 5642

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

I'd suggest writing it like this so you won't have to change anything other than include B if you rename B:

module B
  def access_private_here
    puts self.class::MY_CONST
  end
end

class A
  include B
  private
    MY_CONST = "cat"
end

A.new.access_private_here #=> "cat"

Upvotes: 4

tadman
tadman

Reputation: 211590

If you want to refer to it from another module:

module B
  def access_private_here
    puts A::MY_CONST
  end
end

If you do want to declare it as a private constant, which is highly unusual, you need to go out of your way to do this:

module A
  MY_CONST = 1
  private_constant :MY_CONST
end

At that point it's private, so you can't reference it. As a note, these sorts of things are best shared using methods rather than constants.

Upvotes: 3

Related Questions