tags:

views:

51

answers:

3

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?

+9  A: 

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
+1 great answer. Very complete
Sam Post
Good answer, but you are forgetting `eval`
glebm
@glebm: Yes, and on purpose. I use `eval` when it's the only option available, not otherwise.
Lars Haugseth
true, but just so that the reader knows his enemy I'd mention it :)
glebm
+2  A: 

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
+1  A: 

Use this: http://gist.github.com/621134

Usage:

@sandbox = Script.new(path)
@sandbox::SETTINGS

This way you'll avoid any namespace collision

I don't remember where this file comes from, but I've been using it for a couple of years now.

glebm