メソッドのように呼び出されるクラスを持つ Ruby コードを見てきました。
FactoryGirl(:factory_name) # => returns a factory instance
その「方法」はどのように書きますか?
メソッドのように呼び出されるクラスを持つ Ruby コードを見てきました。
FactoryGirl(:factory_name) # => returns a factory instance
その「方法」はどのように書きますか?
クラスと同じ名前の関数を作成し、そのパラメータをクラスの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
完全を期すために、下部で定義されています。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
このファクトリ関数をオブジェクト クラスに追加できます。
class Object
def FactoryGirl(symbol)
...
end
end