3

メソッドのように呼び出されるクラスを持つ Ruby コードを見てきました。

FactoryGirl(:factory_name) # => returns a factory instance

その「方法」はどのように書きますか?

4

3 に答える 3

3

クラスと同じ名前の関数を作成し、そのパラメータをクラスのnewメソッドに転送するだけです。例えば:

class Foo
  def initialize(x)
    @arg=x
  end

  def to_s
    @arg.to_s
  end
end

def Foo(x)
  Foo.new(x)
end

a = Foo.new(7)
a.class
=> Foo
puts a
=> 7
b = Foo(7)
b.class
=> Foo
puts b
=> 7
于 2012-06-14T15:05:00.017 に答える
3

完全を期すために、下部で定義されています。lib/factory_girl/syntax/vintage.rb

module FactoryGirl
  module Syntax
    module Vintage
      # [other stuff elided]

      # Shortcut for Factory.create.
      #
      # Example:
      #   Factory(:user, name: 'Joe')
      def Factory(name, attrs = {})
        ActiveSupport::Deprecation.warn 'Factory(:name) is deprecated; use FactoryGirl.create(:name) instead.', caller
        FactoryGirl.create(name, attrs)
      end
    end
  end
end
于 2012-06-14T15:12:18.960 に答える
2

このファクトリ関数をオブジェクト クラスに追加できます。

  class Object
    def FactoryGirl(symbol)
      ...
    end
  end
于 2012-06-14T14:49:51.587 に答える