-3

I use this Ruby code when I load value.

request_builder = "#{gateway.camelize}RequestBuilder".constantize

But from time to time value gateway is missing from the yml configuration file. How I can add check is this value present? For example if value gateway is empty I want to print some message and stop code execution.

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

1 Answers1

0

You could just ask gateway:

unless gateway&.empty?

Or with ActiveSupport (Rails):

if gateway.present?

So raise an exception if gateway is not present:

fail "gateway not present" unless gateway.present?
request_builder = "#{gateway.camelize}RequestBuilder".constantize

(Btw fail is an alias of raise. Some people prefer to use raise only inside rescue blocks and fail otherwise, but that's just a matter of taste.)


Update: Removed the & from &.present? since ActiveSupport defines present? on NilClass.

svoop
  • 3,318
  • 1
  • 23
  • 41
  • 1
    No need for lonely operator with `present?`. `gateway.present?` will just work. – Sergio Tulentsev Mar 12 '18 at 13:32
  • Not if the config file doesn't contain that key at all. However, if `gateway` is guaranteed not to be `nil`, yes, the ampersand is obsolete. – svoop Mar 12 '18 at 13:36
  • Try it with nil. – Sergio Tulentsev Mar 12 '18 at 13:37
  • If it's guaranteed to not be nil, this entire question/answer is irrelevant :) – Sergio Tulentsev Mar 12 '18 at 13:38
  • Not really. Say in a Rails app, you have different YAML config files per environment and not all of them hold all the keys. You might want to raise an understandable exception or handle it gracefully if `gateway` is `nil`. Whether it can be `nil` depends on how you parse the YAML and assign the value to `gateway`. – svoop Mar 12 '18 at 13:44
  • What I'm saying is, `nil.present?` won't crash. l̶o̶n̶e̶l̶y̶ safe-navigation operator is redundant there. – Sergio Tulentsev Mar 12 '18 at 13:47
  • Ah, you're right, keep forgetting how "pragmatic" ActiveSupport is. Fixed it in my answer. Thanks @SergioTulentsev – svoop Mar 12 '18 at 18:13