Introduction to dependency injection in Ruby

Christian Paling
Jul 31, 2016 · 3 min read

What is dependency injection

class NotePresenter  def initialize
@note_storage = NoteTextStorage.new
end
def pending_notes
notes = @note_storage.get_all
notes.select { |n| n.pending? }
end
end
class TestStorage

def pending_notes
note1 = Note.new title: 'test', text: 'test', pending: true
note2 = Note.new title: 'test2', text: 'test2', pending: false
end
end

Implementing dependency injection in Ruby

class NotePresenter  def initialize(storage)
@note_storage = storage
end
def pending_notes
notes = @note_storage.get_all
notes.select { |n| n.pending? }
end
end
dependency_container = Dry::Container.new
dependency_container.register('note_storage', -> { NoteTextStorage.new })
AutoInject = Dry::AutoInject(dependency_container)
class NotePresenter
include AutoInject['note_storage']
def pending_notes
notes = note_storage.get_all
notes.select { |n| n.pending? }
end
end
dependency_container = Dry::Container.new
dependency_container.register('note_storage', -> { TestStorage.new })
AutoInject = Dry::AutoInject(dependency_container)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade