25

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?

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
Radek
  • 13,813
  • 52
  • 161
  • 255

3 Answers3

62

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
Lars Haugseth
  • 14,721
  • 2
  • 45
  • 49
6

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)
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
2

A really simple one is to use eval.

config.txt

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

program.rb

configuration = eval(File.read("./config.txt"))
puts configuration['user1']
Darwin
  • 4,686
  • 2
  • 30
  • 22