Skip to content

AaronLasseigne/tash

Repository files navigation

Tash is a hash that allows for transformation of its keys. A transformation block is given to change the key. Keys can be looked up with any value that transforms into the same key. This means a hash can be string/symbol insensitive, case insensitive, can convert camel case JSON keys to snake case Ruby keys, or anything else based on the block you provide.

Version Test


Installation

Add it to your Gemfile:

gem 'tash', '~> 1.0'

Or install it manually:

$ gem install tash --version '~> 1.0'

This project uses Semantic Versioning. Check out GitHub releases for a detailed list of changes.

Usage

Let's say that you wanted to have a hash where the keys are accessible as strings or symbols (i.e. ActiveSupport::HashWithIndifferentAccess).

t = Tash[one: 1, two: 2, &:to_s]
# => {"one"=>1, "two"=>2}

t[:one]
# => 1

t['one']
# => 1

t[:three] = 9 # oops
# => 9

t['three'] = 3
# => 3

t[:three]
# => 3

t['three']
# => 3

Lets say that you recieve a series of camel case JSON keys from an API call but want to access the information with Rubys typical snake case style and symbolized.

json = { "firstName" => "Adam", "lastName" => "DeCobray" }

t = Tash[json] do |key|
  key
    .to_s
    .gsub(/(?<!\A)([A-Z])/, '_\1')
    .downcase
    .to_sym
end

t[:first_name]
# => "Adam"

t['firstName']
# => "Adam"

This also works with pattern matching:

t = Tash[ONE: 1, MORE: 200, &:downcase]

case t
in { One: 1, More: more }
  more
else
  nil
end
# => 200

Tash implements to_hash for implicit hash conversion making it usable nearly everywhere you use a hash.

Tash has every instance method Hash has except for transform_keys and transform_keys!.

API Documentation

Contributing

If you want to contribute to Tash, please read our contribution guidelines. A complete list of contributors is available on GitHub.

License

Tash is licensed under the MIT License.

About

A hash that allows for transformation of its keys.

Resources

License

Stars

Watchers

Forks

Packages

No packages published