gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:55 24 4
gpt4 key购买 nike

我目前正在编写一个脚本(命令行工具)来帮助我管理公开的控制台。

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

$ 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 文件?

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

最佳答案

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

准备 gem 的一个好方法是在 gem 中创建一个 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

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

关于Ruby 脚本,存储 API 登录信息的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22243059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com