After reading "Practical Object-Oriented Design in Ruby" by Sandi Metz, I decided to use DI in a small service in Ruby (Sinatra or Grape for example).
So far, I have come up with a way to inject dependencies to class variables:
# Service Object
class AppClient
cattr_accessor :http_client # class variable to be injected
def self.configure &block # help method to set the class variables
yield(self)
end
def save
response = http_client.put(url, body: body, params: {}) # use (simplified)
end
end
# Initializer
AppClient.configure do |config|
config.http_client = Typhoeus # DI (we inject the dependency here)
end
Do you think this example is a good way to inject dependencies? Do you know other techniques?
Note: I do know that dependency injection is usually unnecessary with Ruby (but this is not the question so is not a duplicated one) Does dependency injection exist in Rails? Ruby dependency injection libraries