Aha

A(ugmented)ha(sh) is a Hash extension library that makes it easy to work with data represented by nested hash maps.

It was largely inspired by Uncle Bob's keynote 'Architecture: the lost years' and the insight that while domain modeling with objects is great, we want to deal with plain data structures at the boundaries of our system.

Installation

gem install aha

or add the following line to your application's Gemfile:

gem 'aha'

and run bundle install from your shell.

Usage

# some data to play with
def data
  {:a  => 'value_1',
   'b' => {:c => 'value_2',
           :d => 'value_3'},
   :e  => {:f => 'value_4',
           :g => {:h => 'value_5'}}}
end

# Destructuring assignment
value_1, value_2, value_3, value_4, value_5
  = data.vals_at :a, ['b', :c, :d], [:e, :f [:g, :h]]

# Get nested values from top level object
data.get_in :e, :g, :h
# => 'value_5'

# Set nested values from top level object
d1 = data
d1.put_in! :e, :g, :h, 'new_value'
d1.get_in :e, :g, :h
# => 'new_value'

# Update nested values from top level object
d2 = data
d2.update_in!(:e, :g, :h) { |v| v * 3 }
d2.get_in :e, :g, :h
# => 'value_5value_5value_5'

# Delete nested values from top level object
d3 = data
d3.delete_in! 'b', :d
d3['b']
# => {:c => 'value_2'}

# Exclude keys from nested hash
d4 = data
d4.exclude! :a, ['b', :c], [:e, :g]
d4
# => {'b' => {:d => 'value_3'}, :e => {:f => 'value_4'}}

# Keep a subset of keys
d5 = data
d5.only :a, [:e, [:g, :h]]
# => {:a => 'value_1', :e => {:g => {:h => 'value_5'}}}

Planned

  • Non-destructive variants of all the existing methods

Contributing

  • If it is a new feature please create an issue first.
  • Fork and send me a pull request. Tests are a must!

License

Copyright © 2014 Mike Jackson.

Distributed under the permissive MIT license.