Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active December 2, 2016 13:36
Show Gist options
  • Save henrik/ce10621f347119d3fba6586725e954bc to your computer and use it in GitHub Desktop.
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…
# Path: foo/bar.rb
class Foo_Bar
def self.hello
puts "Hello from Foo_Bar!"
end
end
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
$ 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