Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save settings as a hash in a external file?

Tags:

ruby

Can I somehow use this

settings = { 

   'user1' => { 'path' => '/','days' => '5' },
   'user2' => { 'path' => '/tmp/','days' => '3' }
}

in a external file as settings?

How can I include this into my script?

like image 709
Radek Avatar asked Sep 11 '25 09:09

Radek


2 Answers

The most common way to store configuration data in Ruby is to use YAML:

settings.yml

user1:
  path: /
  days: 5

user2:
  path: /tmp/
  days: 3

Then load it in your code like this:

require 'yaml'
settings = YAML::load_file "settings.yml"
puts settings.inspect

You can create the YAML file using to_yaml:

File.open("settings.yml", "w") do |file|
  file.write settings.to_yaml
end

That said, you can include straight Ruby code also, using load:

load "settings.rb"

However, you can't access local variables outside the file, so you would have to change your code to use an instance variable or a global variable:

settings.rb

SETTINGS = { 
 'user1' => { 'path' => '/','days' => '5' },
 'user2' => { 'path' => '/tmp/','days' => '3' }
}
@settings = { 'foo' => 1, 'bar' => 2 }

Then load it thus:

load "settings.rb"
puts SETTINGS.inspect
puts @settings.inspect
like image 128
Lars Haugseth Avatar answered Sep 12 '25 23:09

Lars Haugseth


you can also use Marshal

settings = {
   'user1' => { 'path' => '/','days' => '5' },
   'user2' => { 'path' => '/tmp/','days' => '3' }
}
data=Marshal.dump(settings)
open('output', 'wb') { |f| f.puts data }
data=File.read("output")
p Marshal.load(data)
like image 32
ghostdog74 Avatar answered Sep 12 '25 23:09

ghostdog74