Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 独立ruby脚本的配置文件_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 独立ruby脚本的配置文件

Ruby on rails 独立ruby脚本的配置文件,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个在linux服务器上运行的ruby脚本。它没有使用rails或任何东西。它基本上是一个命令行ruby脚本,可以像这样传递参数:/ruby\u script.rb arg1 arg2 如何将参数抽象到配置文件(如yaml文件或其他文件)中?你能举例说明如何做到这一点吗 提前感谢。首先,您可以运行一个独立的脚本来写入YAML配置文件: require "yaml" File.write("path_to_yaml_file", [arg1, arg2].to_yaml) 然后,在应用程序中

我有一个在linux服务器上运行的ruby脚本。它没有使用rails或任何东西。它基本上是一个命令行ruby脚本,可以像这样传递参数:
/ruby\u script.rb arg1 arg2

如何将参数抽象到配置文件(如yaml文件或其他文件)中?你能举例说明如何做到这一点吗


提前感谢。

首先,您可以运行一个独立的脚本来写入YAML配置文件:

require "yaml"
File.write("path_to_yaml_file", [arg1, arg2].to_yaml)
然后,在应用程序中阅读:

require "yaml"
arg1, arg2 = YAML.load_file("path_to_yaml")
# use arg1, arg2
...

您可以使用我作为其中一部分编写的系统,一个独立的Ruby脚本

您的项目应该包含一个带有配置数据的
config.yml
文件,如:

更新程序脚本:
代码URL:https://github.com/NeomindLabs/neomind-dashboard-public
Leftronic仪表板:
仪表板访问键:“bGVmdHJvbmljaXNhd2Vz”#在上查找https://www.leftronic.com/api/
流名称:
CI项目名称的状态:
“项目阿尔法”:项目阿尔法状态
“项目测试版”:项目测试版ci状态
“项目伽马”:项目伽马状态
#等等。
将文件复制到项目中。这是一个非常小的文件,用于加载YAML配置文件

# encoding: utf-8

require 'yaml'

class ConfigLoader
  def initialize
    load_config_data
  end

  def [](name)
    config_for(name)
  end

  def config_for(name)
    @config_data[name]
  end

  private

  def load_config_data
    config_file_path = 'config/config.yml'
    begin
      config_file_contents = File.read(config_file_path)
    rescue Errno::ENOENT
      $stderr.puts "missing config file"
      raise
    end
    @config_data = YAML.load(config_file_contents)
  end
end
最后,在使用配置文件的每个文件中,遵循以下模式(此示例来自该文件):

需要图书馆 使用配置文件中的第一级键加载
CONFIG
常量 使用
CONFIG
读取配置数据
在使用接受答案中的方法读取YAML文件时,我遇到了一个
未定义的局部变量或方法
错误。我用了一种稍微不同的方式:

如上所述写信给它:

require "yaml"
File.write("path/to/yaml", ["test_arg_1", "test_arg_2"].to_yaml)
使用轻微的变化来阅读:

require "yaml"
arg1, arg2 = YAML.load(File.read("path/to/yaml"))

puts arg1
#=> test_arg_1
puts arg2
#=> test_arg_2

写一个yaml然后读取同一个yaml有什么意义?否则,您将无法从该文件中获取数据。您是否希望将某些内容写入文件A,然后通过访问不同的文件B来读取该数据?这没有道理。
  def initialize_updater
    access_key = CONFIG["dashboard access key"]
    @updater = Leftronic.new(access_key)
  end
require "yaml"
File.write("path/to/yaml", ["test_arg_1", "test_arg_2"].to_yaml)
require "yaml"
arg1, arg2 = YAML.load(File.read("path/to/yaml"))

puts arg1
#=> test_arg_1
puts arg2
#=> test_arg_2