Skip to content

Instantly share code, notes, and snippets.

@saturnflyer

saturnflyer/namespace.rb

Last active Jan 13, 2016
Embed
What would you like to do?
ability to create classes and modules in a namespace
module Namespace
class Manager
def initialize(namespace)
@managed = namespace
end
def create_module(name, &block)
mod = Module.new(&block)
@managed.const_set(name, mod)
mod
end
def create_class(name, parent: Object, &block)
klass = Class.new(parent, &block)
@managed.const_set(name, klass)
klass
end
end
def namespace(string, &block)
namespace = string.split('::').inject(Object) do |base, mod|
base.const_get(mod)
end
Manager.new(namespace).instance_eval(&block)
end
end
extend Namespace
class Thing
class Form
end
end
namespace 'Thing::Form' do
create_module(:Mod) do
def hello
'hi'
end
end
create_class(:Klass) do
def hello
'it works'
end
end
end
puts Thing::Form::Mod.instance_method(:hello).bind(self).call
puts Thing::Form::Klass.new.hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment