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

后端 未结 3 1589
时光取名叫无心
时光取名叫无心 2020-12-24 12:44

Can I somehow use this

settings = { 

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


        
相关标签:
3条回答
  • 2020-12-24 13:23

    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']
    
    0 讨论(0)
  • 2020-12-24 13:27

    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)
    
    0 讨论(0)
  • 2020-12-24 13:38

    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
    
    0 讨论(0)
提交回复
热议问题