Skip to content

Instantly share code, notes, and snippets.

@dreoliv
Created July 4, 2012 17:37
Show Gist options
  • Save dreoliv/3048530 to your computer and use it in GitHub Desktop.
Save dreoliv/3048530 to your computer and use it in GitHub Desktop.
Indirect object creation

Inject factory method

Use for spawning multiple objects

class Foo

  attr_writer :bar_source


  private
  
  def bar_source
    @bar_source ||= Bar.public_method(:new)
  end
end

Inject instance

For a has-one relationship

class Secretary
  
  def create_appointment(doctor, patient, appointment=nil)
    appointment ||= Appointment.new
    appointment.tap do |appointment|
      appointment.doctor = doctor
      appointment.patient = patient
    end
  end
  
end

This is a little weird. Check if your class isn't doing too little or if you shouldn't rename things.

Stub complete creation method

For when there's a complete creation method

class Foo; end

before do
Foo.stub(:for_bar).and_return(qux)
end
class Foo

def initialize
  @qux = 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment