Skip to content

Instantly share code, notes, and snippets.

@chikamichi
Created March 26, 2010 13:57
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 chikamichi/344898 to your computer and use it in GitHub Desktop.
Save chikamichi/344898 to your computer and use it in GitHub Desktop.
dynamic instances extending mechanism for Metamorphosis
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