Thor Reading config yaml file for overriding parameters

I am trying to create an executable ruby ​​script using Thor.

I determined the parameters of my task. So far i have something like this

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 

When csv2strings is called without arguments, I would like to call the config task, which would set the option :langs .

I have not yet found a good way to do this.

Any help would be appreciated.

+4
source share
1 answer

I think that you are looking for a way to configure configuration parameters through the command line and through the configuration file.

Here is an example from a diamond master .

  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 

It overrides the options method and combines the values ​​from the configuration file into the hash code of the source parameters.

In your case, the following may work:

 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 

(I recently posted a post on Foreman on my blog that explains this in more detail.)

+5
source

Source: https://habr.com/ru/post/1488545/


All Articles