2014-03-07 51 views
2

我目前正在致力於一個腳本(命令行工具)的工作,以幫助我管理曝光控制檯。Ruby腳本,存儲API的登錄信息的最佳方法?

起初我我用它來登錄到控制檯每次路過三個參數的腳本,例如:

$ nexose-magic.rb -u user -p password -i 192.168.1.2 --display-scans 

這不是很有效,所以我創建了一個config.yml文件存儲控制檯信息在散列中。

$ nexpose-magic.rb -c console --display-scans 

我相信這個工具對管理員有用,所以我想分享一個寶石。我無法弄清楚如何讓我的config.yml文件與gem install一起工作..它無法找到config.yml文件!將它指向我的開發目錄中的相對路徑很容易,但是一旦我創建了一個相對路徑不再那麼相對的gem。我如何將nexpose-magic.rb指向config.yml文件?

有沒有更好的方法來處理這樣的事情?

+2

想到的地方是放在用戶主目錄下的dotfile文件中。 –

回答

0

您可以創建一個包含configure類的gem。這個類有一個load方法,它將一個目錄作爲參數。然後,您可以傳遞您當前正在工作的目錄。

您準備創業板的好方法是在你的寶石打造Configuration單件類:

require 'singleton' 
class Configuration 
    include Singleton 

    attr_accessor :config, :app_path 
    def load(app_path) 
    @app_path = app_path 

    #load the config file and store the data 
    @config = YAML.load_file(File.join(@app_path,'config','config.yml')) 
    end 

end 

在主類:

module MyFancyGem 

    class << self 
    #define a class method that configure the gem 
    def configure(app_path) 
     # Call load method with given path 
     config.load(app_path) 
    end 

    # MyFancyGem.config will refer to the singleton Configuration class 
    def config 
     MyFancyGem::Configuration.instance 
    end 

    end 

end 

用法:

-Working directory 
    - my_new_script 
    - Gemfile 
    - config/ 
    - config.yml 

在my_new_script中:

require 'bundler' 
Bundler.setup(:default) 
require 'my_fancy_gem' 
MyFancyGem.configure(File.join(File.dirname(__FILE__),"./")) #here, you define the path 

MyFancyGem.hello_world 

我希望這已經夠清楚了。我實際上是要寫一篇博客文章來解釋這個特定的問題(我希望能有一個更完整的版本)。讓我知道你是否感興趣!

+0

因此,如果我正在運行ruby的bin目錄中存在的可執行文件,那麼每次運行命令時都會傳遞配置文件參數? – Matthew