DEV Community

loading...

handy Ruby methods #3 - Hash#fetch

andy4thehuynh profile image Andy Huynh Updated on ・1 min read
class StripePaymentIntegration
  def self.enabled?
    ENV["ENABLE_STRIPE_PAYMENT_INTEGRATION"]
  end
end

This code isn't bulletproof. If it's not obvious - let me help you.

This is disabled by default. When we push to production, the app reboots. There exists a small window where ENABLE_STRIPE_PAYMENT_INTEGRATION isn't set. The code technically isn't doing what you're expecting.

Why does the app reboot? Because Heroku dynos automatically restart with every new code release. Here's a short description of Heroku dynos.

If only we can set a default value to avoid to ensure this is enabled when we push. It'd be even better if it was in pure Ruby.

class StripePaymentIntegration
  def self.enabled?
    ENV.fetch("ENABLE_STRIPE_PAYMENT_INTEGRATION", "true")
  end
end

Voila! Understand that ENV serves as a hash-like structure. Thus, it can "fetch" a hash's value given a key. Hash#fetch takes a lookup key in the first parameter and an optional second as a fallback value.

You can deploy and now be sure this works correctly!

I believe you get the most out of a software language by writing it as it's meant to be written. One of the pillars writing good Ruby code is being expressive.

ENV.fetch("ENABLE_STRIPE_PAYMENT_INTEGRATION", "true") comment below if that doesn't express what I'm puttin' down.

Discussion (0)

pic
Editor guide