Skip to content

Instantly share code, notes, and snippets.

@danshultz
Created January 26, 2012 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danshultz/1683178 to your computer and use it in GitHub Desktop.
Save danshultz/1683178 to your computer and use it in GitHub Desktop.
Services and Dependency Injection in Ruby
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
@drydevelopment
Copy link

Can you show me how you'd consume these objects? I'm wondering why we could not just sub-class this out, or pass in optional constructor arguments/hash to get a similar outcome.

@danshultz
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment