Last active
January 13, 2016 21:58
-
-
Save saturnflyer/c5737f832da56a0a2a78 to your computer and use it in GitHub Desktop.
ability to create classes and modules in a namespace
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 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