我见过 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