【问题标题】:How to treat a ruby class as a method?如何将 ruby​​ 类视为方法?
【发布时间】:2012-06-14 14:37:26
【问题描述】:

我见过 Ruby 代码中的类称为类似方法:

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

你是怎么写那个“方法”的?

【问题讨论】:

标签: ruby


【解决方案1】:

您需要做的就是创建一个与类同名的函数,并将其参数转发给类的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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您可以将此工厂函数添加到对象类中:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-17
        • 2016-04-04
        • 2021-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多