【发布时间】:2012-06-14 14:37:26
【问题描述】:
我见过 Ruby 代码中的类称为类似方法:
FactoryGirl(:factory_name) # => returns a factory instance
你是怎么写那个“方法”的?
【问题讨论】:
标签: ruby
我见过 Ruby 代码中的类称为类似方法:
FactoryGirl(:factory_name) # => returns a factory instance
你是怎么写那个“方法”的?
【问题讨论】:
标签: ruby
您需要做的就是创建一个与类同名的函数,并将其参数转发给类的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
【讨论】:
为了完整起见,底部是defined in 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
【讨论】: