gpt4 book ai didi

ruby - Gem 中的配置 block

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:42 24 4
gpt4 key购买 nike

我正在尝试编写我的第一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com