jeudi 4 mai 2017

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

Aucun commentaire:

Enregistrer un commentaire