Thor阅读配置yaml文件以覆盖选项

net*_*tbe 4 ruby command-line thor

我正在尝试使用Thor创建可执行的ruby脚本.

我已经为我的任务定义了选项.到目前为止,我有类似的东西

class Command < Thor

  desc "csv2strings CSV_FILENAME", "convert CSV file to '.strings' file"
  method_option :langs, :type => :hash, :required => true, :aliases => "-L", :desc => "languages to convert"
  ...
  def csv2strings(filename)
    ...
  end

  ...
  def config
    args = options.dup
    args[:file] ||= '.csvconverter.yaml'

    config = YAML::load File.open(args[:file], 'r')
  end
end
Run Code Online (Sandbox Code Playgroud)

csv2strings没有参数的情况下调用时,我希望调用配置任务,这将设置选项:langs.

我还没有找到一个很好的方法来做到这一点.

任何帮助将不胜感激.

Jam*_*Lim 5

我认为您正在寻找一种通过命令行和配置文件设置配置选项的方法.

以下是工头宝石的一个例子.

  def options
    original_options = super
    return original_options unless File.exists?(".foreman")
    defaults = ::YAML::load_file(".foreman") || {}
    Thor::CoreExt::HashWithIndifferentAccess.new(defaults.merge(original_options))
  end
Run Code Online (Sandbox Code Playgroud)

它会覆盖该options方法并将配置文件中的值合并到原始选项哈希中.

在您的情况下,以下可能会起作用:

def csv2strings(name)
  # do something with options
end

private
  def options
    original_options = super
    filename = original_options[:file] || '.csvconverter.yaml'
    return original_options unless File.exists?(filename)
    defaults = ::YAML::load_file(filename) || {}
    defaults.merge(original_options)
    # alternatively, set original_options[:langs] and then return it
  end
Run Code Online (Sandbox Code Playgroud)

(我最近在我的博客上写了一篇关于Foreman的帖子,更详细地解释了这一点.)