如何将ruby类视为一种方法?

时间:2012-06-14 14:37:26

标签: ruby

我见过类似于方法的类的Ruby代码:

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

你怎么写'方法'?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

为了完整性,底部是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

答案 2 :(得分:2)

您可以将此工厂函数添加到Object-class:

  class Object
    def FactoryGirl(symbol)
      ...
    end
  end