在 gem 中放置/访问配置文件的位置? [英] Where to place/access config file in gem?

查看:34
本文介绍了在 gem 中放置/访问配置文件的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写我的第一个 gem,我希望用户通过 config.yml 文件检索和设置特定选项.

I am writing my first gem and I'd like specific options to be retrieved and set by the user through a config.yml file.

这个文件应该放在我的 gem 文件结构中的什么位置,以及在安装我的 gem 时有人如何修改该文件?我猜他们可以在安装 gem 时传入特定的选项,这些选项可以映射到 config.yml 文件,但这怎么可能呢?

Where should this file be placed within my gem file structure and how does someone modify the file when installing my gem? I'm guessing they can pass in specific options when installing the gem, and those options can be mapped to the config.yml file, but how is this possible?

另外,通过 YAML.load_file 检索文件的最佳方法是什么?

Also, is the best way to retrieve the file through YAML.load_file?

我看过 Ryan 关于通过 Bundler 创建 gem 的广播,但他没有涉及这个主题.

I've watched Ryan's railcasts on creating a gem via Bundler, but he doesn't cover this topic.

推荐答案

我有点晚了,但我会留下一个我通常如何处理这个问题的示例实现,以供将来参考.

I'm jumping on this one a little late but I'll leave an example implementation of how I generally handle this, for future reference.

如前所述,您通常希望允许通过文件和哈希进行配置.包含这两种方式非常简单和轻松,因此您应该这样做.

As it was mentioned, you'll normally want to allow configuration through both files and hashes. It's pretty easy and light to include both ways, so you should do it.

这样的事情在大多数情况下都适用于我:

Something like this works for me in most scenarios:

require 'yaml'

module MyGem
  # Configuration defaults
  @config = {
              :log_level => "verbose",
              :min => 0,
              :max => 99 
            }

  @valid_config_keys = @config.keys

  # Configure through hash
  def self.configure(opts = {})
    opts.each {|k,v| @config[k.to_sym] = v if @valid_config_keys.include? k.to_sym}
  end

  # Configure through yaml file
  def self.configure_with(path_to_yaml_file)
    begin
      config = YAML::load(IO.read(path_to_yaml_file))
    rescue Errno::ENOENT
      log(:warning, "YAML configuration file couldn't be found. Using defaults."); return
    rescue Psych::SyntaxError
      log(:warning, "YAML configuration file contains invalid syntax. Using defaults."); return
    end

    configure(config)
  end

  def self.config
    @config
  end
end

另一个最佳实践是为所有配置键设置默认值(如上例所示).这样一来,您就可以让用户自由地配置您的库.

An added best practice would be to have defaults for all your configuration keys(as in the example above). That way, you are giving the user ultimate freedom in how they can configure your library.

这篇关于在 gem 中放置/访问配置文件的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆