chell
chell

Reputation: 7866

how to refine this code mental block Rails

I have these two methods that I would like to combine into one. But for the life of me I can't see how. NOOB big time. any help appreciated.

  def is_active_no_category
      'active' if params[:category].blank?
  end


  def is_active(category)
      'active' if  params[:category] == category.name.parameterize
  end

Upvotes: 0

Views: 29

Answers (1)

Mischa
Mischa

Reputation: 43298

With the below function passing a category as an argument is optional. If you do not pass an argument it will work like your is_active_no_category method. If you do pass an argument. It will work like your is_active method.

def is_active(category = nil)
  'active' if (category.present? && params[:category] == category.name.parameterize) || (category.nil? && params[:category].blank?)
end

You may be able to make the if statement more compact, but you haven't stated the exact requirements for your function, so I gave you the most complete solution.

Upvotes: 2

Related Questions