mr_muscle
mr_muscle

Reputation: 2900

Ruby return unless block

I've got a field from github webhook - webhook.repository.private - which checks if created repository was private (boolean). I want use return if block to handle scenario: check if webhook.repository.private is true and if not call new class PublicRepositoryCreated but if this is true - return and execute fields_hash

code below:

      def required_fields
        PublicRepositoryCreated.new(webhook).call unless webhook.repository.private

        fields_hash
      end

      private

      def fields_hash
        {
          'fields' => {
            'summary' => 'summary',
            'description' => 'description',
            'project' => '123'
          }
        }
      end

Right now it seems that fields_hash is still executed even when webhook.repository.private is false

Upvotes: 1

Views: 1241

Answers (1)

BTL
BTL

Reputation: 4656

You have multiple ways of solving your problem.

You can either :

  1. call your function and return
def required_fields
  PublicRepositoryCreated.new(webhook).call && return unless webhook.repository.private

  fields_hash
end
  1. return your function
def required_fields
  return PublicRepositoryCreated.new(webhook).call unless webhook.repository.private

  fields_hash
end
  1. use a ternary
def required_fields
  webhook.repository.private ? fields_hash : PublicRepositoryCreated.new(webhook).call
end

Upvotes: 2

Related Questions