Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to treat a ruby class as a method?

Tags:

ruby

I've seen Ruby code with classes called like methods:

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

How do you write that 'method'?

like image 694
Mori Avatar asked Apr 06 '26 08:04

Mori


2 Answers

All you need to do is to create a function with the same name as the class and that forwards its parameters to the class' new method. For instance:

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
like image 131
bta Avatar answered Apr 09 '26 01:04

bta


For completeness, it's defined in lib/factory_girl/syntax/vintage.rb at the bottom:

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
like image 28
Dave Newton Avatar answered Apr 09 '26 02:04

Dave Newton