serializable_hash super 如何获取我重写的方法中定义的选项?

How does serializable_hash super gets the options defined in my overridden method?

在活动记录模型中,我们将覆盖 serializable_hash 方法并在根据需要设置选项后调用 super options

通常我们这样做:

def serializable_hash options=nil
    options ||= {
      only: [
        :id,
        :special_instructions
      ],
      include: { images: nil },
      methods: [:catalog_item_name, ]
    }
    super options
  end

但是在其中一个模型中,我们 没有 显式地将 options 传递给 super 方法。尽管如此,它似乎正在工作,就好像我们正在传递选项一样。

阅读 serializable_hash source code 之后,我们似乎找不到任何理由让 options 在 super 方法中正确初始化。

关于这是如何发生的任何提示?

自然地,尝试在 ruby 脚本中重现结构似乎不会以相同的方式发生。 这是我们为试用而编写的内容:

module MyModule
  def my_module_method options=nil
    options ||= { test: 'Test' }
  end
end

class MyTest
  include MyModule

  def my_module_method
    options = { bingo: 'Bingo!' }
    super
  end
end

puts MyTest.new.my_module_method

这将打印 { test: 'Test' },如果我们传递选项 (super options),将打印 { bingo: 'Bingo!' }(正如我们所期望的)

来自(相当旧)pickaxe book (AKA Programming Ruby)

When you invoke super with no arguments, Ruby sends a message to the current object's parent, asking it to invoke a method of the same name as the current method, and passing it the parameters that were passed to the current method.

鉴于此:

class C
  def m(x)
    puts x
  end
end
class D < C
  def m(x)
    super
  end
end
D.new.m(6)

您会看到 6,因为当您不为父版本提供任何显式参数时,D#mx 参数隐含在 superm.

MyTest#my_module_method 定义添加一个参数,您会看到一些东西。