0.0
No commit activity in last 3 years
No release in over 3 years
Converts nested Hashes into a nested struct
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.14
>= 0
~> 10.0
~> 3.0
 Project Readme

HashMangler

Gem Version

A simple gem which converts nested hash into a struct allowing data access with method calls like:

  mangled_hash.users[0].name # => John

instead of doing:

  users_hash[:users][0].fetch(:name) # => John

for a hash:

  users_hash = {
    users: [
      { name: 'John' }
    ]
  }

Gem converts hash key names to snake case and in case of misspelled names is raising NoMethodError.

Installation

Add this line to your application's Gemfile:

gem 'hash_mangler'

And then execute:

$ bundle

Or install it yourself as:

$ gem install hash_mangler

Usage

For a basic convertion from Hash to a nested object:

hm = HashMangler::Mangler.new.mangle(hash)
hm.some_method_name

You can also perform operations on argument hash values by passing a proc to the initialize method:

value_mangler = proc { |o| o.to_s.downcase }  
options = { value_mangler: value_mangler }
hm = HashMangler::Mangler.new(options).mangle(hash)
hm.some_method_name

By default method names are in snake case, to leave them the same as input hash keys:

snake_case_method_names: false

option needs to be passed into initialize like:

options = { snake_case_method_names: false } 
hm = HashMangler::Mangler.new(options).mangle(hash)
hm.someMethodName

Hash can also be mangled with OpenStruct or Hash using struct_class option:

options = { struct_class: OpenStruct }
hm = HashMangler::Mangler.new(options).mangle(hash)
hm.some_method_name

HashMangler::SimpleStruct can also be used instead of OpenStruct when using:

JSON.parse(json, object_class: OpenStruct)

This way a NoMethodError will be raised instead of returning nil when method name does not comply with hash key value.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/smnkrt/hash_mangler.

License

The gem is available as open source under the terms of the MIT License.