Ruby:
Working with YAML
How to:
Ruby comes with a built-in library called Psych for parsing and emitting YAML. To utilize it, you first need to require the YAML standard library. Here’s a basic example to get you started:
require 'yaml'
# Hash to be serialized
person = { name: "John Doe", age: 30, skills: ["Ruby", "JavaScript"] }
# Converting the hash to YAML
yaml_data = person.to_yaml
puts yaml_data
Sample Output:
---
:name: John Doe
:age: 30
:skills:
- Ruby
- JavaScript
To load YAML data back into a Ruby object:
loaded_person = YAML.load(yaml_data)
puts loaded_person
Sample Output:
{name: "John Doe", age: 30, skills: ["Ruby", "JavaScript"]}
Using Third-Party Libraries:
Although the standard library is sufficient for basic tasks, for complex needs you might look into third-party gems like ‘safe_yaml’. To use such libraries, you must first install the gem:
gem install safe_yaml
Then, you can use it to safely load YAML data, mitigating risks like object instantiation from user-controlled sources:
require 'safe_yaml'
safe_loaded_person = SafeYAML.load(yaml_data)
puts safe_loaded_person
Sample Output:
{name: "John Doe", age: 30, skills: ["Ruby", "JavaScript"]}
This approach enhances the security of your YAML handling, making it a good choice for applications that load YAML from untrusted sources.