Can I somehow use this
settings = {
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' =&g开发者_如何学Pythont; '/tmp/','days' => '3' }
}
in a external file as settings?
How can I include this into my script?
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
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)
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']
精彩评论