Reading and Updating Yaml File by Ruby Code

Reading and updating YAML file by ruby code

Switch .load to .load_file and you should be good to go.

#!/usr/bin/env ruby
require 'yaml'
config = YAML.load_file('data.yml')
puts config['last_update']

After running this is what I get

orcus:~ user$ ruby test.rb
# ⇒ some_data

To write the file you will need to open the YAML file and write to the handle. Something like this should work.

require 'yaml'
config = YAML.load_file('data.yml')
puts config['last_update'] #in my file this is set to "some data"
config['last_update'] = "other data"
File.open('data.yml','w') do |h|
h.write config.to_yaml
end

Output was

orcus:~ user$ ruby test.rb
some data
orcus:~ user$ cat data.yml
---
last_update: other data

Update value of key of a yaml file in ruby on rails


    require 'yaml'
data = YAML.load_file "path/to/yml_file.yml"
data["Name"] = ABC
File.open("path/to/yml_file.yml", 'w') { |f| YAML.dump(data, f) }

It will write into yml file. If specified key ("Name") is not present in file, it will write new key value othrwise the existing one will be replaced.

How do I parse a YAML file in Ruby?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in some.yml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

gives me

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

Ruby on Rails: Can you put Ruby code in a YAML config file?

Not normally / directly. I say this because in order to use ruby results you need to use something like ERB first before loading the file. In terms of code, you need to go from something like:

loaded_data = YAML.load_file("my-file.yml")

Or even

loaded_data = YAML.load(File.read("my-file.yml"))

To:

loaded_data = YAML.load(ERB.new(File.read("my-file.yml")).result)

In this specific case, you would have to look at what is loading the file - in some cases,
it may already be designed to load it straight out of the environment or you may need to either:

  1. Monkey Patch the code
  2. Fork + Use your custom version.

Since there are a few plugins that use amazon_s3.yml, It might be worth posting which library you are using that uses it - alternatively, I believe from a quick google that the AWS library lets you define AMAZON_ACCESS_KEY_ID and AMAZON_SECRET_ACCESS_KEY as env vars and it will pick them up out of the box.



Related Topics



Leave a reply



Submit