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 回答