Ruby脚本,存储API登录信息的最佳方法?

Ruby脚本,存储API登录信息的最佳方法?,ruby,api,Ruby,Api,我目前正在编写一个脚本(命令行工具),以帮助我管理expose控制台 起初,每次使用脚本登录控制台时,我都会向脚本传递三个参数,例如: $ nexose-magic.rb -u user -p password -i 192.168.1.2 --display-scans 这不是很有效,所以我创建了一个config.yml文件,将控制台信息存储在散列中 $ nexpose-magic.rb -c console --display-scans 我相信这个工具对管理员会很有用,所以我想在gem

我目前正在编写一个脚本(命令行工具),以帮助我管理expose控制台

起初,每次使用脚本登录控制台时,我都会向脚本传递三个参数,例如:

$ nexose-magic.rb -u user -p password -i 192.168.1.2 --display-scans
这不是很有效,所以我创建了一个config.yml文件,将控制台信息存储在散列中

$ nexpose-magic.rb -c console --display-scans
我相信这个工具对管理员会很有用,所以我想在gem上分享一下。我不知道如何让我的config.yml文件与gem安装一起工作。它找不到config.yml文件!在我的开发目录中,指向相对路径很容易,但一旦我创建了一个gem,相对路径就不再那么相对了。如何将nexpose-magic.rb指向config.yml文件


有没有更好的方法来处理这样的事情?

您可以创建一个包含
配置
类的gem。此类有一个将目录作为参数的
load
方法。然后,您可以传递当前工作的目录

准备gem的一个好方法是在gem中创建一个
Configuration
singleton类:

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
在我的新脚本中:

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

MyFancyGem.hello_world

我希望这足够清楚。实际上,我正要写一篇博文来解释这一点(我希望能有一个更完整的版本)。如果你有兴趣,请告诉我

我想到的地方是用户主目录中的一个点文件。因此,如果我正在运行ruby的bin dir中的一个可执行文件,那么每次运行该命令时,我都会传递config file参数?
require 'bundler'
Bundler.setup(:default)
require 'my_fancy_gem'
MyFancyGem.configure(File.join(File.dirname(__FILE__),"./")) #here, you define the path

MyFancyGem.hello_world