Last active
December 2, 2016 13:36
-
-
Save henrik/ce10621f347119d3fba6586725e954bc to your computer and use it in GitHub Desktop.
Proof-of-concept of using `_` for Ruby class/module namespaces, with Rails-like autoloading, while avoiding the constant lookup gotchas of using `::`. Inspired by how namespaces work in Elixir (no magic; they're just module names that happen to share a prefix). This is the complexity of constant lookups in Ruby: http://cirw.in/blog/constant-look…
This file contains hidden or 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
# Path: foo/bar.rb | |
class Foo_Bar | |
def self.hello | |
puts "Hello from Foo_Bar!" | |
end | |
end |
This file contains hidden or 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 UnderscoreNamespaceAutoloading | |
def const_missing(name) | |
parts = name.to_s.downcase.split("_") | |
path = parts.join("/") + ".rb" | |
if File.exist?(path) | |
require_relative path | |
const_get(name) | |
else | |
super | |
end | |
end | |
end | |
class Object | |
singleton_class.prepend UnderscoreNamespaceAutoloading | |
end | |
Foo_Bar.hello | |
Foo_Baz.hello |
This file contains hidden or 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
$ ruby example.rb | |
Hello from Foo_Bar! | |
example.rb:10:in `const_missing': uninitialized constant Foo_Baz (NameError) | |
Did you mean? Foo_Bar | |
from example.rb:20:in `<main>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment