Ruby 传递部分参数以使用默认值运行

Ruby passing partial args to function with defaults

我是 Capybara 的新手,rspec & Ruby,我有一个填写表格的功能:

def form_fill(name:'James', age:'25', pets:'cat')
    fill_in 'Name', with: name
    fill_in 'Age' , with: age
    fill_in 'Pets', with: pets
end

我想知道要在函数中更改什么,以便我可以修改表单(我已经填写过),再次使用相同的函数。

例如: 我做了form_fill(name:'Bob'),现在我的表格是:

Name   Age    Pets
----   ----   ----
Bob    25     cats

稍后我想更改相同的已保存表格,并且仅通过调用仅带有年龄参数的相同函数来更改年龄:form_fill(age:45).

此时使用默认值将表单更改为:

Name   Age    Pets
----   ----   ----
James  45     cats

所以我想知道如何同时实现与填充剂和修饰剂相同的功能。

看起来你只需要在这里使用一个普通的旧 Ruby 对象 class。首先,我将创建一个 Person class,您将使用它来设置一个人的属性。

class Person
  attr_accessor :name, :age, :pets

  def initialize(name: "James", age: 45, pets: "cat")
    @name = name
    @age = age
    @pets = pets
  end
end

这将允许您执行以下操作:

person = Person.new(name: "Bob")
=> #<Person:0x007fac4bb27128 @age=45, @name="Bob", @pets="cat">

然后在 Capybara 方法中执行此操作:

def form_fill(person)
  fill_in 'Name', with: person.name
  fill_in 'Age' , with: person.age
  fill_in 'Pets', with: person.pets
end

何时修改人物:

person.age = 25
form_fill(person)

希望对您有所帮助!