You can use instance_eval :
class Bar def do_something validator = AllValidator.new.age_validator # Evaluate validator in the context of self. instance_eval &validator end end
If you want to pass arguments (as indicated in the comment below), you can use instance_exec instead of instance_eval if you use Ruby 1.9 or Ruby 1.8.7:
class Bar def do_something validator = AllValidator.new.age_validator # instance_exec is like instance_eval with arguments. instance_exec 5, &validator end end
If you need to make it work with Ruby 1.8.6 and below, it is best to bind proc as a Bar method:
class Bar def do_something self.class.send :define_method, :validate, &AllValidator.new.age_validator self.validate 5 end end
An alternative is to implement instance_exec older versions of Ruby ( example here ). All he does is define the method before calling it and define it after completion.
molf
source share