YAML – Full Length Example
YAML - Full Length Example
Section titled “YAML - Full Length Example”This example demonstrates several YAML features, including nested structures, anchors (&), aliases (*), and merge keys (<<). These features are powerful for creating maintainable and concise configuration files. Anchors and aliases help avoid repetition, while merge keys allow for inheriting properties from other parts of the document.
Consider the following YAML configuration for a database setup across different environments:
defaults: &defaults adapter: postgresql host: localhost pool: 5
development: database: myapp_development <<: *defaults # Merge the 'defaults' here
test: database: myapp_test <<: *defaults # Merge the 'defaults' here pool: 2 # Override the 'pool' value from defaults
production: database: myapp_production adapter: postgresql host: prod-db.example.com pool: 50Let’s break down this example:
&defaults: This is an anchor named ‘defaults’. It marks the mapping that follows (adapter, host, pool) as a reusable block.*defaults: This is an alias. It references the content anchored by ‘defaults’.<<: *defaults: This is a merge key. It instructs the YAML parser to merge the key-value pairs from the aliased ‘defaults’ mapping into the current mapping (‘development’ and ‘test’). Keys in the current mapping will override keys from the merged mapping if they conflict (e.g., ‘pool: 2’ in ‘test’ overrides ‘pool: 5’ from ‘defaults’).
When this YAML is parsed, it effectively expands to the following data structure (conceptually similar to JSON):
{ "defaults": { "adapter": "postgresql", "host": "localhost", "pool": 5 }, "development": { "database": "myapp_development", "adapter": "postgresql", "host": "localhost", "pool": 5 }, "test": { "database": "myapp_test", "adapter": "postgresql", "host": "localhost", "pool": 2 }, "production": { "database": "myapp_production", "adapter": "postgresql", "host": "prod-db.example.com", "pool": 50 }}This example showcases how YAML can be used to create complex yet readable configurations by leveraging its structural and reusability features.