Skip to content

Instantly share code, notes, and snippets.

@ckhrysze
Created February 9, 2012 20:35
Show Gist options
  • Save ckhrysze/1782892 to your computer and use it in GitHub Desktop.
Save ckhrysze/1782892 to your computer and use it in GitHub Desktop.
Playing with dynamic module inclusion
module Alpha
module Bravo
class Charlie
class Delta
ECHO = 'echo'
FOXTROT = 'foxtrot'
end
end
end
end
module DSL
module RubyCode
class CleanRoom < BasicObject
def context
@context ||= Context.new
end
def puts(str)
::Kernel.puts(str)
end
end
class Context
def asdf; 'asdf'; end
def qwer; 'qwer'; end
end
class Runner
def initialize(includes = [])
clean_room_class = Class.new(CleanRoom)
includes.each do |module_name|
clean_room_class.send(:include, full_const_get('Alpha::Bravo'))
end
@clean_room = clean_room_class.new
end
# Allows you to convert from a string representation of a module name
# to that module
#
# @param [String] name Name of the module
# @return [Module] if we have a module, nil otherwise.
#
# @example Convert from "String" to String
# 'full_const_get("String")' #=> String
def full_const_get(name)
return nil if name.nil?
name.split("::").inject(Object) do |mod, name|
mod = mod.const_get(name)
end
end
def execute(code)
@clean_room.instance_eval(code)
end
end
end
end
puts 'Begin code runner'
puts '-'*25
puts
runner = DSL::RubyCode::Runner.new(['Alpha::Bravo'])
runner.execute <<-CODE
puts context.asdf
puts Charlie::Delta::ECHO
CODE
puts
puts '-'*25
puts 'All Done'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment