When I do the following in irb I get this output:
>> class TestMe
>> def new
>> puts 'hi!'
>> end
>> end
=> nil
>> TestMe.new.new
hi!
Additionally:
>> class TestMe
>> end
=> nil
>> TestMe.new.new
NoMethodError: undefined method `new' for #<TestMe:0x00000101038750>
But when I’m writing some code in my text editor of choice that is calling an instance method named new (but is not the Object method new that instantiates new objects) it highlights new as if it were a reserved keyword:
@page = current_user.locations.new
Note that locations here returns a delegator class that does some heavy lifting (via this new method) and eventually does return a Location.new instance with some basic setup data ready to go, but new is not itself being called on a class object. Is this an acceptable use of the method name or will I run into issues with it?
The first call to
.newwill invoke the constructor, and return an instance of your class. The second call to.newwill invoke an instance method on that object. It’s completely acceptable to define anewinstance method.In order to interfere with the constructor, you would have to define a class-level method called
new. That method can invokesuper#new(which invokesClass#new) to perform the actual creation of the object:It’s completely valid to overwrite
newat both an instance and class level, so long as you define your customnewmethod to do something sane.