ruby-style-guide icon indicating copy to clipboard operation
ruby-style-guide copied to clipboard

Add guideline about omitting super arguments

Open Earlopain opened this issue 1 year ago • 2 comments

For https://github.com/rubocop/rubocop/pull/12427 which is the RuboCop implementation of this. I'll just copy the examples over:

def some_method(*args, **kwargs)
  super(*args, **kwargs)
end

# good - implicitly passing all arguments
def method(*args, **kwargs)
  super
end

# good - forwarding a subset of the arguments
def method(*args, **kwargs)
  super(*args)
end

# good - calling super with different arguments
def method(*args, **kwargs)
  super("foo", *args, **kwards)
end

# good - forwarding no arguments
def method(*args, **kwargs)
  super()
end

There's an interesting interaction with blocks that I wasn't previously aware of: they are just always passed, unless explicitly opted out through &nil. Demonstration:

class A
  def foo(*args, **kwargs)
    if block_given?
      pp yield
    else
      pp "No Block"
    end
  end
  
  def bar(...)
    if block_given?
      pp yield
    else
      pp "No Block"
    end
  end
end

class B < A
  def foo(*args, **kwargs)
    super(*args, **kwargs)
    super()
  end
  
  def bar(*args, **kwargs, &blk)
    super(*args, **kwargs, &blk)
    super()
  end
end

B.new.foo("foo", c: "c", d: "d") { "FOO" }
B.new.bar("bar", c: "c", d: "d") { "BAR" }
# => Never prints "No Block"

I've added a callout for this at the end.

Earlopain avatar May 22 '24 16:05 Earlopain