2017-08-24 42 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'方法,这个方法在任何地方都是可用的。这是一个小调整,我给你留下。 –

相关问题