lib/surrogate/endower.rb in surrogate-0.1.0 vs lib/surrogate/endower.rb in surrogate-0.2.0
- old
+ new
@@ -1,8 +1,10 @@
class Surrogate
# adds surrogate behaviour to your class / singleton class / instances
+ #
+ # please refactor me!
class Endower
def self.endow(klass, &playlist)
new(klass, &playlist).endow
end
@@ -58,23 +60,26 @@
def singleton
klass.singleton_class
end
def can_get_a_new(klass)
- klass.define_singleton_method :reprise do
- new_klass = Class.new self
- surrogate = @surrogate
- Surrogate.endow new_klass do
- surrogate.api_methods.each do |method_name, options|
- define method_name, options.to_hash, &options.default_proc
+ klass.extend Module.new {
+ # use a module so that the method is inherited (important for substitutability)
+ def clone
+ new_klass = Class.new self
+ surrogate = @surrogate
+ Surrogate.endow new_klass do
+ surrogate.api_methods.each do |method_name, options|
+ define method_name, options.to_hash, &options.default_proc
+ end
end
+ @hatchery.api_methods.each do |method_name, options|
+ new_klass.define method_name, options.to_hash, &options.default_proc
+ end
+ new_klass
end
- @hatchery.api_methods.each do |method_name, options|
- new_klass.define method_name, options.to_hash, &options.default_proc
- end
- new_klass
- end
+ }
end
def remember_invocations_for_instances_of(klass)
klass.send :define_method, :invocations do |method_name|
@surrogate.invocations method_name
@@ -84,16 +89,19 @@
def a_hatchery_for(klass)
klass.instance_variable_set :@hatchery, Surrogate::Hatchery.new(klass)
end
def hijack_instantiation_of(klass)
- def klass.new(*args)
- instance = allocate
- hatchery = @hatchery
- instance.instance_eval { @surrogate = Hatchling.new instance, hatchery }
- instance.send :initialize, *args
- instance
- end
+ # use a module so that the method is inherited (important for substitutability)
+ klass.extend Module.new {
+ def new(*args)
+ instance = allocate
+ hatchery = @hatchery
+ instance.instance_eval { @surrogate = Hatchling.new instance, hatchery }
+ instance.send :initialize, *args
+ instance
+ end
+ }
end
def enable_defining_methods(klass)
def klass.define(method_name, options={}, &block)
@hatchery.define method_name, options, block