Add helper methods to more easily use public_send with a whitelist

Everyone can contribute. Help move this issue forward while earning points, leveling up and collecting rewards.

By default we disallow the use of public_send as this can lead to security issues. In places where we do need this, we usually use the following pattern:

if some_whitelist.include?(method_name)
  receiver.public_send(method_name) # rubocop: disable GitlabSecurity/PublicSend
end

We should add a method of sorts that allows you to write the following instead:

receiver.send_with_whitelist(method_name, some_whitelist)

This method could be implemented as follows:

class Object
  def send_with_whitelist(name, allowed, *args)
    if allowed.include?(name.to_s)
      public_send(name, *args)
    else
      self
    end
  end
end

Returning self by default means you can do something like this:

thing = thing.send_with_whitelist(:foo, %w(foo bar baz))
Edited by 🤖 GitLab Bot 🤖