Skip to content

Instantly share code, notes, and snippets.

@saturnflyer
Last active January 13, 2016 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saturnflyer/c5737f832da56a0a2a78 to your computer and use it in GitHub Desktop.
Save saturnflyer/c5737f832da56a0a2a78 to your computer and use it in GitHub Desktop.
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