Last active
August 29, 2015 14:11
-
-
Save notahat/c72cee07f9a74e61a2d0 to your computer and use it in GitHub Desktop.
Private classes in Ruby, version 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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