Skip to content

Instantly share code, notes, and snippets.

@alex-fedorov
Last active August 29, 2015 14:22
Show Gist options
  • Save alex-fedorov/b192d8dd58deda202c5d to your computer and use it in GitHub Desktop.
Save alex-fedorov/b192d8dd58deda202c5d to your computer and use it in GitHub Desktop.
DI example
# Without DI:
# It knows what kind of datastore it has
# This way you just mixed URL, HTTP methods and stuff here
class Person
API_URL = "#{ROOT_API_URL}/api/v2/people"
def save
return insert if new?
update
end
def insert
@id = datastore.post(attributes)
end
def update
datastore.put(id, attributes)
end
def datastore
@_datastore ||= RestDataStore.new(API_URL)
end
end
# With DI:
# It doesn't give a shit about what kind of store it has
# Bonus: you can use the same Person class to handle objects from different stores:
# - database
# - REST API
# - xml file
# etc.
class Person
def initialize(datastore)
@datastore = datastore
end
def save
return insert if new?
update
end
def insert
@id = datastore.insert(attributes)
end
def update
datastore.update(id, attributes)
end
private
attr_reader :datastore
end
# Adding DI not through `initialize`
class Person
def initialize(lots_of_attributes)
# ...
end
def with_datastore(datastore)
@datastore = datastore
self
end
def datastore
fail "No datastore injected :(" unless @datastore
@datastore
end
def save
# ...
end
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment