Skip to content

Instantly share code, notes, and snippets.

@esparta esparta/00_README.md
Created Jul 16, 2019

Embed
What would you like to do?
How to make constants really 'private'

How to make constants really 'private'

There's a constant misunderstanding about how private method works...

For example, this DOES NOT make BAR a private constant:

class This
  private
  BAR = 'bar'.freeze
end

puts This::Bar
# => bar

Then how??

Module#private_constant to the rescue

class This
  BAR = 'bar'.freeze
  private_constant :BAR
end

puts This::Bar
# displaying error
# private_c.rb:16 in `<main>': private constant This::Bar reference error
# shell returned 1

This works with any constant, including classes and modules:

# frozen_string_literal: true

class This
  class Other
    class << self
      def foo
        'x'
      end
    end
  end
  private_constant :Other

  def access
    puts Other.foo
  end
end

This.new.access  # Will be ok..
# And this will error
This::Other.foo

Thanks for watching!!

# frozen_string_literal: true
class This
private
BAR = 'bar'.freeze
end
puts This::Bar
# => bar
# frozen_string_literal: true
class This
BAR = 'bar'.freeze
private_constant :BAR
end
puts This::Bar
# displaying error
# private_c.rb:16 in `<main>': private constant This::Bar reference error
# shell returned 1
# frozen_string_literal: true
# Module#private_constant in action
# It works with any constant, including classes and modules
class This
class Other
class << self
def foo
'x'
end
end
end
private_constant :Other
def access
puts Other.foo
end
end
This.new.access # Will be ok..
# And this will error
This::Other.foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.