Create objects with nested brackets on new lines

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the workflows category.

Last Updated: 2024-11-21

I had issues getting ElasticSearch to accept a new port, 443. It seemed to ignore it. Here was my code:

def build
  new(client: Elasticsearch::Client.new(url: elasticsearch_url), port: 443)
end

The issue, as you can see, is that I closed the brackets for Client.new too soon, and therefore the port argument went to my initializer (new) instead, where it had no effect.

Here's the corrected code:

def build
  new(client: Elasticsearch::Client.new(url: elasticsearch_url, port: 443))
end

But such bugs seem subtle and difficult to miss in Ruby. How can I avoid these issues systematically in future?

def build
  client = Elasticsearch::Client.new( url: elasticsearch_url)
  # Now the error is obvious
  new(client: client, port: 443)
end