0

I'm new at Rails... Is there a better way to refactor this code:

  def get_product_price_minimum
    Product.minimum(:price).to_i
  end

  def get_product_price_maximum
    Product.maximum(:price).to_i
  end
2
  • What is the purpose of this two methods, so I can give solution based on purpose. e.g. you want minimum price product Commented Jan 20, 2018 at 12:26
  • 1
    Why are those two methods a problem? Sure, you could mash them together but to what end? Would refactoring make the code easier to read? Easier to use? Easier to debug? Easier to test? Faster? Maybe move them to class methods on Product and call it a day. Refactoring is great but there's not enough there to make it worthwhile (IMO). Commented Jan 20, 2018 at 19:35

2 Answers 2

2

You can define something like "prices" (a vague method name, to avoid using get_ or set_ prefixes) to expect an argument, which would be the maximum or minimum for which to query your model:

def prices(what)
  Product.public_send(what, :price).to_i
end

Then you can use it by passing the minimum or maximum as a symbol or a string.

Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure your function works but you can try (if price is column and price is a int not a string)

def get_product_price_minimum
      Product.order('price').last
end

1 Comment

what about maximum?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.