什么';构建Ruby gem时,最佳的配置模式是什么?

什么';构建Ruby gem时,最佳的配置模式是什么?,ruby,rubygems,Ruby,Rubygems,我目前正在构建一个RubyGem,需要验证配置调用。 我的要求是: 默认值 所需的验证 验证是否包含在值列表中 我的第一个方法如下: 配置.rb module Configuration def define_setting(name, default: nil) class_variable_set("@@#{name}", default) define_singleton_method(name) do class_variable_get("@@#{

我目前正在构建一个RubyGem,需要验证配置调用。 我的要求是:

  • 默认值
  • 所需的验证
  • 验证是否包含在值列表中
我的第一个方法如下:

配置.rb

module Configuration
  def define_setting(name, default: nil)
    class_variable_set("@@#{name}", default)

    define_singleton_method(name) do
      class_variable_get("@@#{name}")
    end

    define_singleton_method("#{name}=") do |value|
      class_variable_set("@@#{name}", value)
    end
  end
end
module Gem
  extend Configuration

  define_setting :api_url, default: DEFAULT_API_URL
end
Gem.configuration do |c|
  c.api_url = ENV['DEFAULT_API_URL']
end
gem.rb

module Configuration
  def define_setting(name, default: nil)
    class_variable_set("@@#{name}", default)

    define_singleton_method(name) do
      class_variable_get("@@#{name}")
    end

    define_singleton_method("#{name}=") do |value|
      class_variable_set("@@#{name}", value)
    end
  end
end
module Gem
  extend Configuration

  define_setting :api_url, default: DEFAULT_API_URL
end
Gem.configuration do |c|
  c.api_url = ENV['DEFAULT_API_URL']
end
gem\u初始值设定项.rb

module Configuration
  def define_setting(name, default: nil)
    class_variable_set("@@#{name}", default)

    define_singleton_method(name) do
      class_variable_get("@@#{name}")
    end

    define_singleton_method("#{name}=") do |value|
      class_variable_set("@@#{name}", value)
    end
  end
end
module Gem
  extend Configuration

  define_setting :api_url, default: DEFAULT_API_URL
end
Gem.configuration do |c|
  c.api_url = ENV['DEFAULT_API_URL']
end
我删除了验证包含的代码,但这非常简单。问题在于尝试验证所需的值。我基本上可以向
define\u setting
方法添加
required:true
参数,将其保存在数组中,并检查
configuration
调用是否设置了所有必需的值。我觉得这有点太复杂了

另一种方法是移动
配置
模块内的所有配置逻辑,创建一个初始化方法,并检查
api_url
是否通过

class Configuration
  attr_accessor :api_url

  def initialize(api_url)
    @api_url = api_url

    message = "Configuration value 'api_url' is required."
    raise StandardError, message if @api_url.to_s.empty?
  end
end
初始值设定项看起来像:

Gem::Configuration.new(api_url: ENV['DEFAULT_API_URL'])

希望我的解释有道理。有人知道什么是解决这个问题的最佳方法吗?

我可能不完全理解这个问题,但一个简单的解决方法可能是使用“fetch”,它检查是否设置了内容(特别是环境变量)。因此,如果将初始值设定项设置为
Gem::Configuration.new(api\u url:ENV.fetch('DEFAULT\u api\u url'))
,则如果缺少环境变量,将引发异常。建议使用环境变量,但没有任何方法阻止用户放置字符串,那么
fetch
检查将被忽略。