Created
October 23, 2011 18:33
-
-
Save iande/1307682 to your computer and use it in GitHub Desktop.
Module Maker
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 SomeAPI | |
| def self.get_var mod, meth | |
| vars_for(mod)[meth] | |
| end | |
| def self.set_var mod, meth, val | |
| vars_for(mod)[meth] = val | |
| end | |
| def self.vars_for mod | |
| @all_my_vars ||= {} | |
| @all_my_vars[mod] ||= {} | |
| end | |
| end | |
| module ModuleMaker | |
| def self.make_module mod_name, method_list | |
| mod = Module.new do | |
| method_list.each do |meth_name| | |
| define_method("#{meth_name}") { SomeAPI.get_var(mod_name, meth_name) } | |
| define_method("#{meth_name}=") { |val| SomeAPI.set_var(mod_name, meth_name, val) } | |
| end | |
| end | |
| mod.send :extend, mod | |
| Object.const_set mod_name, mod | |
| end | |
| end | |
| ### Test it | |
| ModuleMaker.make_module "Runtime", ["runtime", "foobar"] | |
| puts Runtime.methods.inspect | |
| Runtime.foobar = 42 | |
| Runtime.runtime = "Hello World" | |
| puts "foobar is == #{Runtime.foobar}" | |
| puts "runtime is == #{Runtime.runtime}" | |
| # chaos@godel:scraps$ ruby module_maker.rb | |
| # [:runtime, :runtime=, :foobar, :foobar=, ... ] | |
| # foobar is == 42 | |
| # runtime is == Hello World |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment