【问题标题】:Fabrication gem: how to pass custom values to init_with()?Fabrication gem:如何将自定义值传递给 init_with()?
【发布时间】:2013-12-22 16:48:34
【问题描述】:

Fabrication gem 允许我们将自定义参数传递给我们正在构造的类的构造函数:

on_init { init_with('something', true) }

但是如何在对象生成时为init_with 传递自定义值?

对于对象字段,我可以这样做,但是有没有办法将值传递给init_with?

Fabricate(:foobar, attr1: 'something', attr2: true)

【问题讨论】:

    标签: ruby fabrication-gem


    【解决方案1】:

    您可以在 Fabricate 时使用块语法,就像在定义 Fabricator 时一样。

    Fabricate(:foobar, attr1: 'something', attr2: true) do
      on_init { init_with('another', 'thing') }
    end
    

    【讨论】:

    • 感谢 Paul,但不幸的是,我使用的类有很多构造函数参数,我想将它们全部保留在制造商定义中,并且在制造时只更改 1 或 2.. . 有没有办法做到这一点?
    【解决方案2】:

    据我所知,这是不可能的。

      def build_instance_with_init_callback(callback)
        self._instance = _klass.new(*callback.call)
        set_attributes
      end
    

    你被你在制造商定义中使用的东西卡住了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      相关资源
      最近更新 更多