Created
January 26, 2012 15:07
-
-
Save danshultz/1683178 to your computer and use it in GitHub Desktop.
Services and Dependency Injection in Ruby
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
class Discussion | |
def initialize(roundtable, resources_proc, themes_proc) | |
@subject = roundtable.subject | |
@body = roundtable.body | |
@resource_proc = resources_proc | |
@themes_proc = themes_proc | |
end | |
def resources | |
@resources_proc.call | |
end | |
def themes_proc | |
@themes_proc.call | |
end | |
end | |
class LazyLoadService | |
def get_discussions(*args) | |
roundtable = Roundtable.find(1) | |
Discussion.new(roundtable, lambda{ get_resources }, lambda{ get_themes }) | |
end | |
def get_resources | |
end | |
def get_themes | |
end | |
end | |
class NotLazyLoadedService | |
def get_discussions(*args) | |
roundtable = Roundtable.find(1) | |
Discussion.new(roundtable, get_resources, get_themes) | |
end | |
def get_resources | |
end | |
def get_themes | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what do you mean how the objects would be consumed?
I think subclassing this Discussion class is an option but not optimal as this would require you subclass for each different way of handling the the internalized collections.
The point of the Discussion class is to provide a contract layer for interacting with the data from the domain.
You could also pass in option constructor args - such as if a collection is passed in, then use the passed in collection or pull it from somewhere off the "roundtable" argument passed in but then you do not allow the option of lazy loading from multiple sources.
This code allows you to lazy load or eager load and you can do it from any source the particular service determines as acceptable.
The result of the procs passed in must respect a common interface however.