2014-03-07 55 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