1
To better understand the meta-programming in Ruby I would like to make an object, when instantiated, delegate all methods of an object passed as parameter. And your class will pass to delegate the methods that the class of it contains. But I would like the Object and Class methods,: send and object_id, which may cause errors if changed, are set
I thought of something like:
def delegate_all
delegate_instance if !@delegated
delegate_singleton if !@@delegated
end
def delegate_instance
((@model.class.instance_methods-Object.instance_methods)-Class.instance_methods).each do |name|
name = name.to_sym
puts name.to_s
self.class.send(:define_method, name){ |*args|
method = @model.method name
#if method.arity > 0
method.call args
#else
# method.call
#end
}
end
@delegated = true
end
def delegate_singleton
((@model.class.singleton_methods-Class.singleton_methods)-Object.singleton_methods).each do |name|
name = name.to_sym
puts name.to_s
self.class.define_singleton_method(name){|*args|
name = name.to_sym
method = @model.singleton_method name
#if method.arity > 0
method.call args
#else
# method.call
#end
}
end
@@delegated = true
end
Does anyone have any idea how I can do this? , but I should also consider methods with parameters.
I implemented my delegator this way, but I want to delegate a model of Ruby on Rails, and I would like to redecorate it as if it were the model, e.g.: '<%= render my_presenter %>', some hint of how to implement it
– user5020
As far as I can see, there’s no reason why a delegate should fail to function in this case. What exactly is the problem you have? (It would be a good thing to open a new question on this)
– Guilherme Bernal
I resolved to change the methods 'methods', 'instance_methods', 'singleton_methods' by increasing the methods of the delegated object
– user5020