Jeff Nyman
Jeff Nyman

Reputation: 890

Tightening Up Ruby Code, Making Small Methods

I have a method that is reported by RuboCop as too long: we are only allowed seven lines per method. Here's the offending method:

def on(definition, visit = false, &block)
  if @active.is_a?(definition)
    block.call @active if block
    return @active
  end

  @active = definition.new
  @active.load if visit

  block.call @active if block

  @active
end

I was going to convert the top if condition to a guard clause, but I don't see how to do that.

I tried combining lines 7 and 8 into this:

@active = definition.new().load if visit

but that most definitely does not work.

I can't leave RuboCop violations active nor can I change the tolerances.

Upvotes: 1

Views: 147

Answers (1)

Pardeep Dhingra
Pardeep Dhingra

Reputation: 3946

This will reduce 2 lines:

def on(definition, visit = false, &block)
  unless @active.is_a?(definition)  
    @active = definition.new
    @active.load if visit
  end

  block.call @active if block
  @active
end

Upvotes: 5

Related Questions