3

所以我已经浏览过 Traiblazer 和 Reform 文档,我经常看到这种代码

class AlbumForm < Reform::Form
  collection :songs, populate_if_empty: :populate_songs! do
    property :name
  end

  def populate_songs!(fragment:, **)
    Song.find_by(name: fragment["name"]) or Song.new
  end
end

注意def populate_songs!(fragment:, **)定义?

我很清楚**others捕获所有其他关键字参数的双 splat 命名参数(如 )。但我从来没有见过**一个人,没有名字。

所以我的两个问题是:

  1. **在上面的块中是什么意思?
  2. 为什么使用这种语法?
4

1 回答 1

9

上面的块是什么**意思?

这是一个 kwsplat,但没有指定名称。因此,此方法将接受任意一组关键字参数并忽略除:fragment.

为什么使用这种语法?

忽略你不感兴趣的论点。


一个小演示

class Person
  attr_reader :name, :age

  def initialize(name:, age:)
    @name = name
    @age = age
  end

  def description
    "name: #{name}, age: #{age}"
  end
end

class Rapper < Person
  def initialize(name:, **)
    name = "Lil #{name}" # amend one argument
    super # send name and the rest (however many there are) to super
  end
end

Person.new(name: 'John', age: 25).description # => "name: John, age: 25"
Rapper.new(name: 'John', age: 25).description # => "name: Lil John, age: 25"
于 2017-08-16T08:54:57.893 回答