Skip to content

Instantly share code, notes, and snippets.

@FilBot3
Last active February 10, 2016 15:20
Show Gist options
  • Select an option

  • Save FilBot3/1ca3f8b2a1514dd47665 to your computer and use it in GitHub Desktop.

Select an option

Save FilBot3/1ca3f8b2a1514dd47665 to your computer and use it in GitHub Desktop.
Writing and Reading YAML from both Ruby code, and YAML Markup
#!/usr/bin/env ruby
#
#
#
require 'yaml'
require 'fileutils'
def create_config_file
default_options = {
"ruby_dir" => "#{ENV['HOME']}/rubies",
"ruby_config" => "ruby_thinger.rb",
"ruby_exec" => "ruby.exe"
}.to_yaml
config_file = open("#{ENV['HOME']}/.ruby_config/ruby_config.yml", 'w')
config_file.write default_options
config_file.close
end
puts "=> Setting Variables"
yaml_config_file = "ruby_config.yml"
yaml_config_dir = "#{ENV['HOME']}/.ruby_config"
puts "=> Config location: #{yaml_config_dir}/#{yaml_config_file}"
puts "=> Checking if config Directory exists."
unless File.directory?(yaml_config_dir)
puts "=> Creating config directory."
FileUtils::mkdir_p yaml_config_dir
end
puts "=> Checking for config file."
unless File.exists?("#{yaml_config_dir}/#{yaml_config_file}")
puts "=> Creating config file"
create_config_file
end
puts "=> Reading configuration file."
read_yaml_config_file = YAML::load(File.read("#{yaml_config_dir}/#{yaml_config_file}"))
puts "=> Displaying the contents."
puts read_yaml_config_file
#!/usr/bin/env ruby
#
#
#
require 'yaml'
options = {
"loglocation" => "C:/location",
"logname" => "logfile",
"strings" => ['foo', 'bar'],
"hashinhash" => {
"location" => "location_file"
}
}.to_yaml
puts options
yaml_file = open('yaml_config.yml', 'w')
yaml_file.write(options)
yaml_file.close
read_yaml_file = YAML::load(File.open('yaml_config.yml'))
puts "#{read_yaml_file}"
hash_from_yaml = read_yaml_file
puts hash_from_yaml
---
loglocation: C:/location
logname: logfile
strings:
- foo
- bar
hashinhash:
location: location_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment