Reputation: 1173
I have a ruby script that runs on a linux server. Its not using rails or anything. Its basically a commandline ruby script that can be passed arguments like this: ./ruby_script.rb arg1 arg2
How can I abstract away the arguments into a configuration file such as a yaml file or something? Can you provide an example of how this can be done?
Thank you in advance.
Upvotes: 5
Views: 8082
Reputation: 4734
I encountered an undefined local variable or method
error when reading from the YAML file using the method in the accepted answer. I did it in a slightly different way:
Write to it as above:
require "yaml"
File.write("path/to/yaml", ["test_arg_1", "test_arg_2"].to_yaml)
Read from using a slight variation:
require "yaml"
arg1, arg2 = YAML.load(File.read("path/to/yaml"))
puts arg1
#=> test_arg_1
puts arg2
#=> test_arg_2
Upvotes: 0
Reputation: 30388
You can use the system I wrote as part of neomind-dashboard-public, a standalone Ruby script under the open-source MIT License.
Your project’s config
folder should contain a config.yml
file with your configuration data, like this:
updater script:
code URL: https://github.com/NeomindLabs/neomind-dashboard-public
Leftronic dashboard:
dashboard access key: 'bGVmdHJvbmljaXNhd2Vz' # find on https://www.leftronic.com/api/
stream names:
statuses for CI project names:
"Project Alpha": project_alpha_ci_status
"Project Beta": project_beta_ci_status
"Project Gamma": project_gamma_ci_status
# etc.
Copy the file lib/config_loader.rb
to your project. It’s a very small file that uses the built-in yaml
library to load the YAML config file.
# 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
Finally, in each file that uses the config file, follow this pattern (this example comes from the file lib/dashboard_updater.rb
):
require_relative 'config_loader'
CONFIG
constant with your first-level key in the config fileclass DashboardUpdater
CONFIG = ConfigLoader.new.config_for("Leftronic dashboard")
CONFIG
to read configuration data def initialize_updater
access_key = CONFIG["dashboard access key"]
@updater = Leftronic.new(access_key)
end
Upvotes: 3
Reputation: 168071
First, you can run an independent script that writes to a YAML configuration file:
require "yaml"
File.write("path_to_yaml_file", [arg1, arg2].to_yaml)
Then, read it within your app:
require "yaml"
arg1, arg2 = YAML.load_file("path_to_yaml")
# use arg1, arg2
...
Upvotes: 8