spinlock
spinlock

Reputation: 3947

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!

Upvotes: 2

Views: 187

Answers (2)

David Unric
David Unric

Reputation: 7719

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.

Upvotes: 3

tralston
tralston

Reputation: 3035

Not a total solution according to your problem, but a lot less to type:

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

Upvotes: 0

Related Questions