Skip to content

Instantly share code, notes, and snippets.

@esparta
Created July 16, 2019 17:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esparta/cbe6288c4a2c34d99c504095db17110e to your computer and use it in GitHub Desktop.
Save esparta/cbe6288c4a2c34d99c504095db17110e to your computer and use it in GitHub Desktop.
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