Created
March 26, 2010 13:57
-
-
Save chikamichi/344898 to your computer and use it in GitHub Desktop.
dynamic instances extending mechanism for Metamorphosis
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
require 'facets/kernel/constant' | |
require 'active_support/core_ext/module/attribute_accessors' | |
module Metamorphosis | |
module Injector | |
@@receiver = "Foo" | |
def clutch cst_path, *directives, &blk | |
raise ArgumentError unless cst = Object.constant([@@receiver, cst_path].join("::")) | |
raise ArgumentError unless cst.is_a? Class or cst.is_a? Module | |
# maybe that's not *that* safe, so I should see | |
# what's possible with trace_var. Idée, aussi : | |
# placer l'ensemble du code de slash dans un fiber | |
# ou un thread quelconque, bref un truc qui | |
# garantirait l'adressage. Mais je sais pas si ça | |
# règle le problème des var. globales. | |
$m = Module.new | |
$m.module_eval(&blk) | |
if directives.include? :instances | |
# hophop les instances | |
cst.extend(Module.new do | |
def new *args, &block | |
o = super | |
o.extend($m) | |
o | |
end | |
end) | |
else | |
cst.extend($m) | |
end | |
end | |
end | |
include Injector | |
end | |
module Foo | |
class Bar | |
def say what | |
puts what | |
end | |
end | |
end | |
module Foo | |
extend Metamorphosis | |
#puts Bar.new.instance_eval("class << self; self; end").ancestors.inspect | |
Bar.new.say "hello" | |
puts | |
clutch "Bar", :instances do | |
puts "slashed! backward:" | |
def say what | |
super what.reverse | |
end | |
end | |
#puts Bar.new.instance_eval("class << self; self; end").ancestors.inspect | |
Bar.new.say "hello" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment