Search code examples
rubyrefactoringrubocopkeyword-argument

How do you refactor long ruby method signatures like this one


How can I clean up this ruby method signature?

def card(title: nil, textured: nil, threed: true,
         borderless: false, bodyless: false, title_classes: ['card-header'])

The problem is that I get a linting/rubocop warning:

Metrics/ParameterLists: Avoid parameter lists longer than 5 parameters. [6/5]

The reason I have so many keyword arguments for my method is, I made the method really flexible. It's powerful.


Solution

  • Try creating a case class/data class with those attributes.

    class CardProperties
      attr_accessor :title, :textured, :threed, :borderless, :bodyless, :title_classes
    end
    

    Create a new CardProperties and pass it to the card method:

    card_properties = CardProperties.new
    card_properties.title = ''
    ....
    
    card(card_properties)