Skip to content

Instantly share code, notes, and snippets.

@notahat
Last active August 29, 2015 14:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notahat/c72cee07f9a74e61a2d0 to your computer and use it in GitHub Desktop.
Save notahat/c72cee07f9a74e61a2d0 to your computer and use it in GitHub Desktop.
Private classes in Ruby, version 2
module PrivateClass
def self.included(mod)
*parent, child = mod.name.split("::")
Object.const_get(parent.join("::")).private_constant(child)
end
end
module Container
class PublicThing
def hello
PrivateThing.new.hello
end
end
class PrivateThing
include PrivateClass # Mark this class as private at the top, not the bottom.
def hello
"Hello, world!"
end
end
# private_constant :PrivateThing <-- Normally you'd have to do this.
end
p Container::PublicThing.new.hello # => "Hello, world!"
p Container::PrivateThing.new.hello # => NameError!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment