在閱讀Sandi Metz的「面向對象的Ruby實用設計」之後,我決定在Ruby中使用一個小型服務(例如Sinatra或Grape)。在不使用DI框架的情況下在Ruby中注入依賴關係的技術
到目前爲止,我想出了一個辦法注入依賴於類變量:
# 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
你覺得這個例子是注入依賴的好辦法?你知道其他技術嗎?
注:我知道,依賴注入通常是用Ruby不必要的(但這不是問題等都不是複製一個) Does dependency injection exist in Rails? Ruby dependency injection libraries