在哪里放置/访问configuration文件在gem?

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

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

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

我曾经看过Ryan的电视广播,通过Bundler创造一个gem,但他没有涉及这个话题。

我稍微晚了一点,但是我会留下一个例子来说明如何处理这个问题,以备将来参考。

如前所述,您通常会希望允许通过文件和哈希进行configuration。 包括两种方式都很简单,所以你应该这样做。

像这样的东西在大多数情况下适用于我:

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 

增加的最佳做法是对所有configuration密钥进行默认设置(如上例所示)。 这样,你就可以给用户极大的自由,让他们可以configuration你的库。

如果你的gem包含一个可以被用户交互运行的命令,那么最好在第一次运行时提示任何必要的细节。 一个保存configuration的好地方就是将用户的主目录作为点文件。

如果你的gem纯粹是作为库的其他代码使用,那么应该允许configuration作为散列或类似的东西传入。

作为一个gem,你需要让人们与他们想要的接口。 你不能假设任何types的应用程序结构。 而是公开一个允许开发人员传递选项散列的API,或者一个可以读取和分析的自己的YAML文件的path。

但试图从gembuild立文件命名约定可能不是你想要的。

另一种模式不使用configuration文件:

 YourGem.configure do |config| config.api_key = 'your_key_here' end 

https://robots.thoughtbot.com/mygem-configure-block