Skip to content

Instantly share code, notes, and snippets.

@SamSaffron
Created February 13, 2025 00:06
Show Gist options
  • Save SamSaffron/f41d2963f5053fa2477d1852d04cd925 to your computer and use it in GitHub Desktop.
Save SamSaffron/f41d2963f5053fa2477d1852d04cd925 to your computer and use it in GitHub Desktop.
psych_pure
require "psych"
require "psych/pure"
# Let's create a rich YAML document with various types and comments
yaml_source = <<~YAML
# Configuration for our awesome application
---
database: # Database settings
host: localhost # Can be changed for production
port: 5432 # Default PostgreSQL port
credentials:
username: admin # Super user access
password: secret123 # TODO: Move to env vars!
# Feature flags and settings
features:
enabled_modules: # Current active modules
- authentication # Required for security
- reporting # Business intelligence
- api # External integration
rate_limiting: # API rate limiting
enabled: true # Protect against abuse
max_requests: 1000 # Requests per hour
# Environment-specific configurations
environments:
production: &prod # Production environment
url: https://prod.example.com
workers: 8 # Optimal for our current server
staging: # Staging environment
<<: *prod # Inherit from production
url: https://staging.example.com
workers: 4 # Reduced workers for staging
YAML
# Load the YAML with comments
config = Psych::Pure.load(yaml_source, comments: true, aliases: true)
puts "=== Original Configuration ==="
puts Psych::Pure.dump(config)
# Make some modifications to demonstrate comment preservation
# and structure modification
# Update some values
config["database"]["port"] = 5433
config["features"]["rate_limiting"]["max_requests"] = 1500
# Add new elements
config["features"]["enabled_modules"] << "monitoring"
config["database"]["pool_size"] = 25
# Modify nested structure
config["environments"]["development"] = {
"url" => "http://localhost:3000",
"workers" => 2
}
# Output the modified configuration
puts "=== Modified Configuration ==="
puts Psych::Pure.dump(config)
# Let's also demonstrate accessing the structure
puts "\n=== Current Settings ==="
puts "Database Port: #{config["database"]["port"]}"
puts "Enabled Modules: #{config["features"]["enabled_modules"].join(", ")}"
puts "Production Workers: #{config["environments"]["production"]["workers"]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment