John Smith
John Smith

Reputation: 6259

Run code in block only when certain condition

Here I want to show you a demo code:

if ENV["PRODUCTION"]
  user.apply_discount!
  product.update!
else
 VCR.use_cassette(vcr_cassette) do
    user.apply_discount!
    product.update!
 end
end

So basically two times I have there the same code:

   user.apply_discount!
   product.update!

How can I prevent this duplication of code? How would you do it? I was thinking of putting the code inside a Block and then either call it directly or in the block. Here's an example:

actions =  Proc.new do
  user.apply_discount!
  product.update!
end

if ENV["PRODUCTION"]
  actions.call
else
 VCR.use_cassette(vcr_cassette) do
    actions.call
 end
end

Do you have another idea? Better solution? Thanks

Upvotes: 0

Views: 107

Answers (2)

SteveTurczyn
SteveTurczyn

Reputation: 36860

Andrey's answer is excellent and should be accepted.

But just want to point out that you can convert a proc to a block instead of calling a proc in a block...

 VCR.use_cassette(vcr_cassette, &actions)

I think the explicit call is better, but just wanted to point out an alternative technique.

Upvotes: 2

Andrey Deineko
Andrey Deineko

Reputation: 52357

Your version is explicit and readable.

The only thing I'd do is moving it to a general method:

def do_env_specific_stuff(stuff)
  ENV('PRODUCTION') ? stuff.call : VCR.use_cassette(vcr_cassette) { stuff.call }
end

Then:

stuff = proc do
  user.apply_discount!
  product.update!
end

do_env_specific_stuff(stuff)

Upvotes: 3

Related Questions