• Stars
    star
    160
  • Rank 234,703 (Top 5 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 15 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Recursive Merging for Ruby Hashes

DeepMerge

Gem Version CI

Deep Merge is a simple set of utility functions for Hash. It permits you to merge elements inside a hash together recursively. The manner by which it does this is somewhat arbitrary (since there is no defining standard for this) but it should end up being pretty intuitive and do what you expect.

You can learn a lot more about this by reading the test file. It's pretty well documented and has many examples of various merges from very simple to pretty complex.

The primary need that caused me to write this library is the merging of elements coming from HTTP parameters and related stored parameters in session. This lets a user build up a set of parameters over time, modifying individual items.

DeepMerge Core Documentation

The deep_merge! method permits merging of arbitrary child elements. The two top level elements must be hashes. These hashes can contain unlimited (to stack limit) levels of child elements. These child elements do not have to be of the same type. Where child elements are of the same type, deep_merge will attempt to merge them together. Where child elements are not of the same type, deep_merge will skip or optionally overwrite the destination element with the contents of the source element at that level. For example,

source = {:x => [4, 5, '6'], :y => 2}
dest   = {:x => [1, 2, 3],   :y => [7, 8, 9]}
dest.deep_merge!(source)
# => {:x => [1, 2, 3, 4, 5, '6'], :y => 2}

By default, deep_merge! will overwrite any unmergeables and merge everything else. To avoid this, use deep_merge (no bang/exclamation mark).

Options

Options are specified in the last parameter passed, which should be in hash format

hash.deep_merge!({:x => [1, 2]}, {:knockout_prefix => '--'})
Option Default Description
:preserve_unmergeables false Set to true to skip any unmergeable elements from source
:knockout_prefix nil Set to string value to signify prefix which deletes elements from existing element
:overwrite_arrays false Set to true if you want to avoid merging arrays
:unpack_arrays nil Set to string value to run Array.join then String.split against all arrays
:sort_merged_arrays false Set to true to sort all arrays that are merged together
:merge_hash_arrays false Set to true to merge hashes within arrays
:extend_existing_arrays false Set to true to extend existing arrays, instead of overwriting them
:keep_array_duplicates false Set to true to keep duplicate entries in arrays, instead of coalescing them
:merge_nil_values false Set to true to merge nil hash values, overwriting a possibly non-nil value
:merge_debug false Set to true to get console output of merge process for debugging

:knockout_prefix

Provides a way to remove elements from an existing Hash by specifying them in a special way in the incoming hash.

source = {:x => ['--1', '3']}
dest   = {:x => ['1', '2']}
dest.deep_merge!(source, :knockout_prefix => "--")
# => {:x => ['2', '3']}

Additionally, if the knockout_prefix is passed alone as a string, it will cause the entire element to be removed.

source = {:x => '--'}
dest   = {:x => [1, 2, 3]}
dest.deep_merge!(source, :knockout_prefix => "--")
# => {:x => ""}

Note that the method ko_deep_merge! defaults the knockout prefix to "--" for convenience.

source = {:x => ['--1', '3']}
dest   = {:x => ['1', '2']}
dest.ko_deep_merge!(source)
# => {:x => ['2', '3']}

:overwrite_arrays

Provides a way to replace Arrays instead of having them merge together.

source = {:x => ['1', '2']}
dest   = {:x => ['3', '4']}
dest.deep_merge!(source, :overwrite_arrays => true)
# => {:x => ['1', '2']}

:unpack_arrays

Permits compound elements to be passed in as strings and to be converted into discrete array elements.

source = {:x => ['5', '6', '7,8']}
dest   = {:x => ['1,2,3', '4']}
dest.deep_merge!(source, :unpack_arrays => ',')
# => {:x => ['1', '2', '3', '4', '5', '6', '7', '8'}

The original purpose for this option is when receiving data from an HTML form, this makes it easy for a checkbox to pass multiple values from within a single HTML element.

:merge_hash_arrays

Merges hashes within arrays.

source = {:x => [{:z => 2}]}
dest   = {:x => [{:y => 1}]}
dest.deep_merge!(source, :merge_hash_arrays => true)
# => {:x => [{:y => 1, :z => 2}]}

:extend_existing_arrays

Adds source elements to existing arrays, instead of overwriting them.

source = {:x => "4" }
dest   = {:x => ["1", "2", "3"]}
dest.deep_merge!(source, :extend_existing_arrays => true)
# => {:x => ["1", "2", "3", "4"]}

:keep_array_duplicates

Keeps duplicate entries in arrays, instead of coalescing them.

By default, without this option, duplicate entries are coalesced.

source = {:x => ["2", "3"]}
dest   = {:x => ["1", "2"]}
dest.deep_merge!(source)
# => {:x => ["1", "2", "3"]}

With this option they are kept.

source = {:x => ["2", "3"]}
dest   = {:x => ["1", "2"]}
dest.deep_merge!(source, :keep_array_duplicates => true)
# => {:x => ["1", "2", "2", "3"]}

:merge_nil_values

Allows nil hash values to be merged.

By default, without this option, nil hash values in the source are ignored.

source = {:x => nil}
dest   = {:x => "1"}
dest.deep_merge!(source)
# => {:x => "1"}

With this option, nil values will overwrite existing values.

source = {:x => nil}
dest   = {:x => "1"}
dest.deep_merge!(source, :merge_nil_values => true)
# => {:x => nil}

Using deep_merge in Rails

To avoid conflict with ActiveSupport, load deep_merge via:

require 'deep_merge/rails_compat'

In a Gemfile:

gem "deep_merge", :require => 'deep_merge/rails_compat'

The deep_merge methods will then be defined as

Hash#deeper_merge
Hash#deeper_merge!
Hash#ko_deeper_merge!

Availability

deep_merge was written by Steve Midgley, and is now maintained by Daniel DeLeo. The official home of deep_merge on the internet is now https://github.com/danielsdeleo/deep_merge

License

Copyright (c) 2008-2016 Steve Midgley, released under the MIT license

More Repositories

1

Decider

Flexible and Extensible Machine Learning in Ruby
Ruby
383
star
2

qusion

Using AMQP as a Queuing Backend for Web Apps Should Be Easy
Ruby
111
star
3

critical

Infrastructure Monitoring As Code
Ruby
68
star
4

moqueue

Mocktacular Companion to AMQP Library. Happy TATFTing!
Ruby
67
star
5

knife-plugins

my .chef/plugins/knife/
Ruby
27
star
6

nom_nom_nom

A Simple Status Server for Chef
JavaScript
22
star
7

cookbooks

Opscode Cookbooks for Chef
Ruby
12
star
8

partials

Demo of Template Partials in Chef 11
Ruby
12
star
9

knife-boxer

Frictionless Chef Environments via Checksum-Versioned Cookbooks
Ruby
10
star
10

omnibus-rubies

Matrix of Ruby/Rubygems Versions in Omnibus Form
Ruby
8
star
11

chef-workflow2-prototype

demoware
Ruby
7
star
12

teeth

Fast parsing of log files in Ruby
C
6
star
13

policyfile-jenkins-demo

demo app for policyfiles
Ruby
4
star
14

gem-mirror-tools

Scripts and Hacks to make Gem Mirroring Work
Ruby
2
star
15

acts_as_bourbon

GitHub Recommendation Contest
2
star
16

chef-data-bindings

Data Binding DSL for Chef: Make cookbooks more readable, portable, and maintainable
Ruby
2
star
17

kallistec-thor-tasks

My Own System Thor Tasks
2
star
18

resource-tracking-demo

work in progress
Ruby
1
star
19

QusionTestHarness

A Basic Rails App That I Use to Test Qusion
Ruby
1
star
20

seth

sethsethsethsethseth
Ruby
1
star
21

exampleproject

A bunch of slow running specs including one that randomly passes and fails. For demonstrating distributed CI.
Ruby
1
star
22

rubygems-json-list

JSON output for gem list
Ruby
1
star
23

docsite

Automated RDoc Site Generator
Ruby
1
star
24

queue-patch

Helps me stay on top of pull requests for opscode/chef
Ruby
1
star
25

omnibus-rubygems-mirror

Omnibus Builds for a Gem Mirror Server using gem-mirror-tools
Ruby
1
star
26

panopticon

Get performance statistics on remote servers using the magic of Nanite
Ruby
1
star