โฏ๏ธ Psych::Merge
if ci_badges.map(&:color).detect { it != "green"} โ๏ธ let me know on Discord or RubyForum, as I may have missed the notification.
if ci_badges.map(&:color).all? { it == "green"} ๐๏ธ send money so I can do more of this. FLOSS maintenance is now my full-time job.
๐ฃ How will this project approach the September 2025 hostile takeover of RubyGems? ๐๏ธ
I've summarized my thoughts in this blog post.
๐ป Synopsis

Psych::Merge intelligently merges two versions of a YAML file using Psych-backed AST analysis. It is built on ast-merge and tree_haver, and shares YAML-family behavior with yaml-merge.
psych-merge is a YAML provider gem, not an alternate home for YAML merge
semantics. Psych-specific code should be isolated behind its TreeHaver backend
adapter. Merge behavior should consume normalized YAML-family owners and
source-preserving edit plans supplied by the StructuredMerge stack. Partial YAML
insertion, replacement, and removal should route through ast-crispr rather
than converting documents to Ruby objects and serializing them with Psych.dump.
Key Features
- Psych-Powered: Uses Ruby's built-in Psych parser for YAML AST analysis
- YAML-Aware: Understands YAML structure including mappings, sequences, and scalars
- YAML Family Behavior: Delegates shared YAML merge semantics to
yaml-merge - Intelligent: Matches nodes by structural signatures
- Fuzzy Key Matching:
MappingMatchRefinermatches similar keys (e.g.,database_urlโdb_url) using Levenshtein distance for typos and naming convention differences - Comment-Preserving: Comments are preserved in their context
- Freeze Block Support: Respects freeze markers (default:
psych-merge:freeze/psych-merge:unfreeze) for merge control - customizable to match your project's conventions - Full Provenance: Tracks origin of every node
- StructuredMerge Native: Depends on
ast-merge,tree_haver,yaml-merge, and Ruby's built-inpsych -
Customizable:
- `signature_generator` - callable custom signature generators - `preference` - setting of `:template`, `:destination`, or a Hash for per-node-type preferences - `node_splitter` - Hash mapping node types to callables for per-node-type merge customization (see [ast-merge][ast-merge] docs) - `add_template_only_nodes` - setting to retain nodes that do not exist in destination - `freeze_token` - customize freeze block markers (default: `"psych-merge"`) - `match_refiners` - array of refiners for fuzzy matching (e.g., `MappingMatchRefiner`)
Supported Node Types
| Node Type | Signature Format | Matching Behavior |
|---|---|---|
| Mapping | [:mapping, key_signatures...] |
Mappings match by their key structure |
| Sequence | [:sequence, element_count] |
Sequences match by position and type |
| Scalar | [:scalar, value] |
Scalars match by value |
| Alias | [:alias, anchor] |
Aliases match by anchor name |
Example
require "psych/merge"
template = File.read("template.yml")
destination = File.read("destination.yml")
merger = Psych::Merge::SmartMerger.new(template, destination)
result = merger.merge
File.write("merged.yml", result.to_yaml)
๐ก Info you can shake a stick at
| Tokens to Remember | |
|---|---|
| Works with MRI Ruby 4 | |
| Support & Community | |
| Source | |
| Documentation | |
| Compliance | |
| Style | |
| Maintainer ๐๏ธ | |
... ๐ |
Compatibility
Compatible with MRI Ruby 4.0.0+, and concordant releases of JRuby, and TruffleRuby.
CI workflows and Appraisals are generated for MRI Ruby 4.0.0+.
This test floor is configured by ruby.test_minimum in .kettle-jem.yml and
may be higher than the gem's runtime compatibility floor when legacy Rubies are
not practical for the current toolchain.
The amazing test matrix is powered by the kettle-dev stack.
How kettle-dev manages complexity in tests
| Gem | Source | Role | Total downloads |
|---|---|---|---|
| appraisal2 | GitHub | multi-dependency Appraisal matrix generation | |
| appraisal2-rubocop | GitHub | RuboCop Appraisal generator integration | |
| kettle-dev | GitHub | development, release, and CI workflow tooling | |
| kettle-jem | GitHub | Appraisals & CI workflow templates | |
| kettle-soup-cover | GitHub | SimpleCov coverage policy and reporting | |
| kettle-test | GitHub | standard test runner and coverage harness | |
| rubocop-lts | GitHub | Ruby-version-aware linting | |
| turbo_tests2 | GitHub | parallel test execution |
โจ Installation
Install the gem and add to the application's Gemfile by executing:
bundle add psych-merge
If bundler is not being used to manage dependencies, install the gem by executing:
gem install psych-merge
โ๏ธ Configuration
Signature Match Preference
Control which version to use when nodes have matching signatures but different content:
# Use template version (for config updates)
merger = Psych::Merge::SmartMerger.new(
template,
destination,
preference: :template,
)
# Use destination version (default - preserve customizations)
merger = Psych::Merge::SmartMerger.new(
template,
destination,
preference: :destination,
)
Template-Only Nodes
Control whether to add nodes that only exist in the template:
# Add template-only nodes
merger = Psych::Merge::SmartMerger.new(
template,
destination,
add_template_only_nodes: true,
)
Custom Freeze Token
Use a custom freeze token to avoid conflicts with other tools:
merger = Psych::Merge::SmartMerger.new(
template,
destination,
freeze_token: "my-project",
)
# Now looks for: # my-project:freeze and # my-project:unfreeze
Mapping Match Refiner
When YAML mapping entries (key-value pairs) don't match by exact key name, the
MappingMatchRefiner uses fuzzy matching to pair entries with:
- Similar key names (e.g.,
database_urlvsdb_url) - Keys with typos or naming convention differences
- Renamed keys that contain similar values
# Enable mapping fuzzy matching
merger = Psych::Merge::SmartMerger.new(
template,
destination,
match_refiners: [
Psych::Merge::MappingMatchRefiner.new(threshold: 0.5),
],
)
MappingMatchRefiner Options
| Option | Default | Description |
|---|---|---|
threshold |
0.5 | Minimum similarity score (0.0-1.0) to accept a match |
key_weight |
0.7 | Weight for key name similarity |
value_weight |
0.3 | Weight for value similarity |
# Custom weights for key-centric matching
refiner = Psych::Merge::MappingMatchRefiner.new(
threshold: 0.6,
key_weight: 0.8, # Focus more on key names
value_weight: 0.2, # Less focus on values
)
Debug Logging
Enable debug logging to see merge decisions:
export PSYCH_MERGE_DEBUG=1
๐ง Basic Usage
Merging Two YAML Files
require "psych/merge"
template_content = File.read("template.yml")
dest_content = File.read("destination.yml")
merger = Psych::Merge::SmartMerger.new(template_content, dest_content)
result = merger.merge
File.write("merged.yml", result.to_yaml)
Analyzing a YAML File
require "psych/merge"
source = File.read("config.yml")
analysis = Psych::Merge::FileAnalysis.new(source)
# Iterate over all top-level nodes
analysis.statements.each do |node|
sig = analysis.generate_signature(node)
puts "#{node.class}: #{sig.inspect}"
end
# Get freeze blocks
analysis.freeze_blocks.each do |freeze_node|
puts "Protected: lines #{freeze_node.start_line}-#{freeze_node.end_line}"
end
Fuzzy Key Matching
When keys are renamed between template and destination, use the MappingMatchRefiner:
require "psych/merge"
template = <<~YAML
database_url: postgres://localhost/app
cache_ttl: 3600
api_endpoint: https://api.example.com
YAML
destination = <<~YAML
db_url: postgres://localhost/custom
cache_timeout: 7200
service_endpoint: https://custom.example.com
YAML
# Default merge won't match keys (names differ)
# Use MappingMatchRefiner for fuzzy matching
merger = Psych::Merge::SmartMerger.new(
template,
destination,
match_refiners: [
Psych::Merge::MappingMatchRefiner.new(threshold: 0.5),
],
)
result = merger.merge
# Keys are matched despite name differences:
# - database_url โ db_url (similar: "database" ~ "db")
# - cache_ttl โ cache_timeout (similar: "ttl" ~ "timeout")
# - api_endpoint โ service_endpoint (similar: "endpoint")
Freeze Block Example
# Application configuration
app_name: MyApp
# psych-merge:freeze Secret configuration
database:
host: production-db.example.com
password: super-secret-password
# psych-merge:unfreeze
logging:
level: info
format: json
๐ Security
See SECURITY.md.
๐ค Contributing
If you need some ideas of where to help, you could work on adding more code coverage, or if it is already ๐ฏ (see below) check issues or PRs, or use the gem and think about how it could be better.
We so if you make changes, remember to update it.
See CONTRIBUTING.md for more detailed instructions.
Code Coverage
Coverage service badges
๐ Versioning
This library follows for its public API where practical.
For most applications, prefer the Pessimistic Version Constraint with two digits of precision.
For example:
spec.add_dependency("psych-merge", "~> 7.0")
๐ Is "Platform Support" part of the public API? More details inside.
Dropping support for a platform can be a breaking change for affected users. If a release changes supported platforms, it should be called out clearly in the changelog and versioned with that impact in mind.
To get a better understanding of how SemVer is intended to work over a project's lifetime, read this article from the creator of SemVer:
See CHANGELOG.md for a list of releases.
๐ License
The gem is available under the following licenses: AGPL-3.0-only, PolyForm-Small-Business-1.0.0. See LICENSE.md for details.
If none of the available licenses suit your use case, please contact us to discuss a custom commercial license.
