How can I create a setter method for a new object with default values?

In my test file, I have:

def default_product()
  Product.new(title: "default title",
              description: "default description",
              price:       1,
              image_url:   'default_url.png')
end

and would like to turn it into a method that can be called either without args, in which case the default attrs would be set, or with args, such as:

default_product(price: 100)

in which case the default price would be overridden by the argument.

What would be the correct way to achieve this?

1 answer

  • answered 2018-01-11 19:41 mudasobwa

    Make use of default keyword parameters:

    def default_product(
        title: "default title",
        description: "default description",
        price: 1,
        image_url: 'default_url.png')
      Product.new(
        title: title,
        description: description,
        price: price,
        image_url: image_url)
    end
    

    And call it like: default_product(title: "Another title").


    Sidenote: the proper approach would be probably to use FactoryBot.