-
-
Save alex-fedorov/b192d8dd58deda202c5d to your computer and use it in GitHub Desktop.
DI example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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