Search code examples
rubyblock

How can I use a block to change the execution context in ruby?


I'm creating a factory for an account object and I'm setting the name like this:

name { "#{Faker::Hacker.ingverb} #{Faker::Hacker.adjective} #{Faker::Hacker.noun}" }

Is there a way to use a block to change the execution context to eliminate the redundant Faker::Hacker calls? I'd like to end up with something like this:

name { Faker::Hacker { "#{ingverb} #{adjective} #{noun}" } }

Thanks!


Solution

  • It looks like you are sending methods to a class/module, so your example may be simply rewritten with use of Module#class_eval method:

    name { Faker::Hacker.class_eval { "#{ingverb} #{adjective} #{noun}" } }

    would invoke methods in the block passed to class_eval on Faker::Hacker class.