Thor Reading config yaml file to override options
Asked Answered
R

1

5

I am trying to create a executable ruby script using Thor.

I have defined the options for 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 the config task to be invoked, which would set the option :langs.

I haven't yet found a good way to do it.

Any help will be appreciated.

Ragan answered 27/6, 2013 at 16:37 Comment(0)
P
7

I think you are looking for a way to set configuration options via the command line and via a configuration file.

Here is an example from the 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

It overrides the options method and merges values from a configuration file into the original options hash.

In your case, the following might 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 wrote a post about Foreman on my blog that explains this in more detail.)

Prudie answered 31/7, 2013 at 0:13 Comment(1)
thanks that did the trick! However i had to handle required options in the csv2strings method options method was called after the required check. So if you have any solution to improve that just let me knowRagan

© 2022 - 2024 — McMap. All rights reserved.