tanvir2362
tanvir2362

Reputation: 76

Is there a DRY way to do this in Ruby on Rails

I have a method which is taking optional arguments. And in the method I am doing query on the optional arguments like this:

    def filter_element(param1, *param2)
      param2[0].empty? ? filtered_element = Model_class.where('city = ?',   param1) : filtered_element = Model_class.where('city = ? and price <= ?', param1, param2[0].to_i)
    end

This is an example with one optional arguments passed into the method.

My question is, if i have more than one optional arguments and want to use it in the query arguments depending on its presence, how can I do that?

I know i can use if, elsif etc. But I want to use a DRY way to do it.

I am pretty sure there is a way, but couldn't find anything related to it.

Upvotes: 0

Views: 98

Answers (1)

Zh Kostev
Zh Kostev

Reputation: 588

I think this can be done differently

#it's better to pass arguments not like array, but as hash
def filter_element(city, options = {})
  scope = Model_class.where(city:  city)
  scope = scope.where('price <= ?', options[:price].to_i) if options[:price].present?
  #some more scope limitation here

  scope
end

element = filter_element('Minsk', price: 500)

Upvotes: 1

Related Questions