I've seen Ruby code with classes called like methods:
FactoryGirl(:factory_name) # => returns a factory instance
How do you write that 'method'?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With