2017-08-24 62 views
0

我在寫一個將與AWS Kinesis交互的庫(包裝器)。我希望庫可以像Rollbar和許多其他庫一樣進行配置。如何在Rails初始化程序中使庫可配置

我也在調查the code並試圖瞭解他們是如何做到的。不過,我不認爲我完全理解它。我認爲他們正在使用中間件來處理這個問題,但不知道如何爲我的用例進行配置。

我會希望有一個文件.../initializers/firehose.rb和內容可以是這個樣子:

Firehose.configure do |config| 
    config.stream_name = ENV['AWS_KINESIS_FIREHOSE_STREAM'] 
    config.region = ENV['AWS_KINESIS_FIREHOSE_REGION'] 
    #.. more config here 
end 

有沒有人這樣做呢?

回答

1

我認爲他們使用的中間件來處理這個

不,沒有中間件。這是一個簡單的紅寶石block usage

下面是最小/準系統實現的外觀。

class Configuration 
    attr_accessor :host, :port 
end 

class MyService 
    attr_reader :configuration 

    def initialize 
    @configuration = Configuration.new 
    end 

    def configure(&block) 
    block.call(configuration) 
    end 
end 

service = MyService.new 

service.configuration # => #<Configuration:0x007fefa9084530> 
service.configuration.host # => nil 


service.configure do |config| 
    config.host = 'http://example.com' 
    config.port = 8080 
end 

service.configuration # => #<Configuration:0x007fefa9084530 @host="http://example.com", @port=8080> 
service.configuration.host # => "http://example.com" 

正如你所看到的,這裏沒有什麼複雜的。只是傳遞物體。

+0

噢,我明白了,我對這個'service'對象在代碼中其他任何地方的可用性沒有疑問? – aks

+1

@aks:通常,你在類本身(而不是它的實例)上有這個'configure'方法,這個方法在任何地方都是可用的。這是一個小調整,我給你留下。 –

相關問題