dimanche 2 décembre 2018

How do I refactor this bulky set of if statements?

I have the following code that works, but I would like it to be more DRY and elegant. It feels ugly with lots of code smells.

Ideally I don't want to use CASE statements because that doesn't feel quite ruby-ish either.

if @property_status.eql? :rent
  if @property_type.eql? :residential
    @results = @search.results.for_rent.residential.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  elsif @property_type.eql? :commercial
    @results = @search.results.for_rent.commercial.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  else
    @results = @search.results.for_rent.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  end
elsif @property_status.eql? :sale
  if @property_type.eql? :residential
    @results = @search.results.for_sale.residential.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  elsif @property_type.eql? :commercial
    @results = @search.results.for_sale.commercial.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  else
    @results = @search.results.for_sale.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  end
else
  @results = @search.results.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
end

Thoughts?

Aucun commentaire:

Enregistrer un commentaire