ruby - Gem 中的配置 block

标签 ruby gem

我正在尝试编写我的第一个 gem,但对典型配置 block 的工作方式有点困惑。为了说明,我想要的是编写类似

MyGem.configure do |c|
    c.property1 = 1
    c.property2 = 'some string'
end

我的 ruby​​ 知识不够深,所以虽然我很乐意使用 block ,但我不确定如何编写需要 block 的代码。

如何以这种方式编写要配置的“MyGem”类(大概通过实例变量)?

最佳答案

这可能是实现您的示例的方式:

class MyGem
  Config = Struct.new :property1, :property2  # => MyGem::Config

  def self.configure(&config_block)
    config_block.call config         # => "some string"
  end                                # => :configure

  def self.config
    @config ||= Config.new  # => #<struct MyGem::Config property1=nil, property2=nil>, #<struct MyGem::Config property1=1, property2="some string">
  end                       # => :config
end                         # => :config

MyGem.configure do |c|         # => MyGem
  c.property1 = 1              # => 1
  c.property2 = 'some string'  # => "some string"
end                            # => "some string"

MyGem.config  # => #<struct MyGem::Config property1=1, property2="some string">

但我也提倡在实例而不是类上存储状态:

class MyGem
  Config = Struct.new :property1, :property2  # => MyGem::Config
  def initialize(&config_block)
    config_block.call config                  # => "some string"
  end                                         # => :initialize

  def config
    @config ||= Config.new  # => #<struct MyGem::Config property1=nil, property2=nil>, #<struct MyGem::Config property1=1, property2="some string">
  end                       # => :config
end                         # => :config

instance = MyGem.new do |c|    # => MyGem
  c.property1 = 1              # => 1
  c.property2 = 'some string'  # => "some string"
end                            # => #<MyGem:0x007fc1691ecb20 @config=#<struct MyGem::Config property1=1, property2="some string">>

instance.config  # => #<struct MyGem::Config property1=1, property2="some string">

如果你这样做,你就没有全局状态。请注意,我们可以有多个不同的配置(例如,每个客户端都有自己的配置,或者您想编写多个测试,但现在每个都有破坏其他配置的风险)。我写了一篇博客,介绍了我想到的实现单例模式的许多方法,以及为什么不应该这样做:http://blog.8thlight.com/josh-cheek/2012/10/20/implementing-and-testing-the-singleton-pattern-in-ruby.html

关于ruby - Gem 中的配置 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28177847/

相关文章:

ruby-on-rails - nokogiri gem 安装问题

ruby - 通过已定义数组元素的子字符串从已定义范围返回子数组

ruby-on-rails - Openshift 上的 Ruby "bundle install"错误

ruby-on-rails - 如何检查准备好更新的 gem ?

ios - Pod install private pods URI::InvalidURIError - 错误的 URI(不是 URI?)

ruby-on-rails - 调试器-linecache 安装错误

Ruby:如何在哈希结构中进行过滤以获取所有 < >"1"的键?

ruby - 枚举器如何在 Ruby 1.9.1 中工作?

ruby - ruby 队列不是线程安全的,为什么队列不同步?

ruby-on-rails - bundle install --deployment和bundle pack有什么区别