ruby – Thor阅读配置yaml文件以覆盖选项
发布时间:2020-12-17 02:38:51 所属栏目:百科 来源:网络整理
导读:我正在尝试使用Thor创建可执行的 ruby脚本. 我已经为我的任务定义了选项.到目前为止,我有类似的东西 class Command Thor desc "csv2strings CSV_FILENAME","convert CSV file to '.strings' file" method_option :langs,:type = :hash,:required = true,:ali
我正在尝试使用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 当没有参数调用csv2strings时,我希望调用config任务,这将设置选项:langs. 我还没有找到一个很好的方法来做到这一点. 任何帮助将不胜感激. 解决方法
我认为您正在寻找一种通过命令行和配置文件设置配置选项的方法.
这是foreman gem的一个例子. 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 它会覆盖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 (我最近在我的博客上写了一篇关于Foreman的帖子,更详细地解释了这一点.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |