2013-06-27 27 views
4

我正在嘗試使用Thor創建可執行的ruby腳本。Thor讀取配置yaml文件以覆蓋選項

我已經爲我的任務定義了選項。到目前爲止,我有這樣的事情

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被稱爲不帶參數,我想調用的配置任務,這將設置選項:langs

我還沒有找到一個好方法來做到這一點。

任何幫助將不勝感激。

回答

5

我認爲你正在尋找一種方法來通過命令行和配置文件設置配置選項。

以下是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

+1

感謝該訣竅!然而,我必須處理'csv2strings'方法選項中的必需選項,方法在所需的檢查後被調用。所以,如果你有任何解決方案來改善,只是讓我知道 – netbe