File: README — Documentation by YARD 0.9.43

# 🐍 SnakyHash

This library is similar in purpose to the HashWithIndifferentAccess that is famously used in Rails, but does a lot more.

This gem is used by `oauth` and `oauth2` gems to normalize hash keys to `snake_case` and lookups,
and provide a nice psuedo-object interface.

It can be thought of as a mashup of:

- `Rash` (specifically the `rash_alt` flavor), which is a special `Mash`, made popular by the `hashie` gem, and
- `serialized_hashie` gem by krystal, rewritten, with some behavior changes

Classes that `include SnakyHash::Snake.new` should inherit from `Hashie::Mash`.

## New for v2.0.2: Serialization Support

The serialization support is set to `false` by default, for backwards compatibility, but may be switched to `true` in the next major release, which will be v3. Example:

    # This class has `dump` and `load` abilities!
    class MyStringKeyedHash < Hashie::Mash
      include SnakyHash::Snake.new(
        key_type: :string,
        serializer: true,
      )
    end

✨ Also new dump & load plugin extensions to control the way your data is dumped and loaded.

### Note for use with oauth2 gem

The serializer is being introduced as a disabled option for backwards compatibility.
In snaky_hash v3 it will default to `true`.
If you want to start using the serializer immediately, reopen the `SnakyHash::StringKeyed` class and add the `SnakyHash::Serializer` module like this:

    SnakyHash::StringKeyed.class_eval do
      extend SnakyHash::Serializer
    end

or you can create a custom class

    class MyHash < Hashie::Mash
      include SnakyHash::Snake.new(key_type: :string, serializer: true)
      # Which is the same as:
      # include SnakyHash::Snake.new(key_type: :string)
      # extend SnakyHash::Serializer
    end

You can then add serialization extensions as needed. See serialization and extensions for more.

Federated DVCS Repository | Status | Issues | PRs | Wiki | CI | Discussions
--- | --- | --- | --- | --- | --- | ---
🧪 oauth-xx/snaky_hash on GitLab | The Truth | 💚 | 💚 | 💚 | 🏀 Tiny Matrix | ➖
🧊 oauth-xx/snaky_hash on CodeBerg | An Ethical Mirror (Donate) | ➖ | 💚 | ➖ | ⭕️ No Matrix | ➖
🐙 oauth-xx/snaky_hash on GitHub | A Dirty Mirror | 💚 | 💚 | ➖ | 💯 Full Matrix | ➖
🤼 OAuth Ruby Google Group | “Active” | ➖ | ➖ | ➖ | ➖ | 💚
🎮️ Discord Server |  | Let’s | talk | about | this | library!

## Upgrading Runtime Gem Dependencies

Due to oauth and oauth2 gems depending on this gem,
this project sits underneath a large portion of the authorization systems on the internet.

That means it is painful for the Ruby community when this gem forces updates to its runtime dependencies.

As a result, great care, and a lot of time, have been invested to ensure this gem is working with all the
leading versions per each minor version of Ruby of all the runtime dependencies it can install with.

What does that mean specifically for the runtime dependencies?

We have 100% test coverage of lines and branches, and this test suite runs across a large matrix
covering the latest patch for each of the following minor versions:

- MRI Ruby @ v2.3, v2.4, v2.5, v2.6, v2.7, v3.0, v3.1, v3.2, v3.3, v3.4, HEAD
  - NOTE: This gem will still install on ruby v2.2, but vanilla GitHub Actions no longer supports testing against it, so YMMV.
- JRuby @ v9.2, v9.3, v9.4, v10.0, HEAD
- TruffleRuby @ v23.1, v23.2, HEAD
- gem `hashie` @ v0, v1, v2, v3, v4, v5, HEAD ⏩️ hashie/hashie
- gem `version_gem` - @v1, HEAD ⏩️ oauth-xx/version_gem

NOTE: `version_gem`, and this library, were both extracted from the ouaht2 gem. They are part of the `oauth-xx` org,
and are developed in tight collaboration with the oauth and oauth2 gems.

### You should upgrade this gem with confidence*.

- This gem follows a strict & correct (according to the maintainer of SemVer; more info) interpretation of SemVer.
  - Dropping support for any of the runtime dependency versions above will be a major version bump.
  - If you aren’t on one of the minor versions above, make getting there a priority.
- You should upgrade the dependencies of this gem with confidence*.
- Please do upgrade, and then, when it goes smooth as butter please sponsor me. Thanks!

* MIT license; I am unable to make guarantees.

🚚 Test matrix brought to you by | 🔎 appraisal++
--- | ---
Adds back support for old Rubies | ✨ appraisal PR #250
Adds support for `eval_gemfile` | ✨ appraisal PR #248
Please review | my PRs!

## 💡 Info you can shake a stick at

Tokens to Remember |
--- | ---
Works with JRuby |
Works with Truffle Ruby |
Works with MRI Ruby 3 |
Works with MRI Ruby 2 |
Source |
Documentation |
Compliance |
Style |
Support |
Enterprise Support | 💡Subscribe for support guarantees covering all FLOSS dependencies! 💡Tidelift is part of Sonar! 💡Tidelift pays maintainers to maintain the software you depend on! 📊`@`Pointy Haired Boss: An enterprise support subscription is “never gonna let you down”, and supports open source maintainers!
Comrade BDFL 🎖️ |
`...` 💖 | 🧊 🐙 🛖 🧪

## ✨ Installation

Install the gem and add to the application’s Gemfile by executing:

    $ bundle add snaky_hash

If bundler is not being used to manage dependencies, install the gem by executing:

    $ gem install snaky_hash

### 🔒 Secure Installation

`snaky_hash` is cryptographically signed, and has verifiable SHA-256 and SHA-512 checksums by
stone_checksums. Be sure the gem you install hasn’t been tampered with
by following the instructions below.

Add my public key (if you haven’t already, expires 2045-04-29) as a trusted certificate:

    gem cert --add <(curl -Ls https://raw.github.com/oauth-xx/snaky_hash/main/certs/pboling.pem)

You only need to do that once. Then proceed to install with:

    gem install snaky_hash -P MediumSecurity

The `MediumSecurity` trust profile will verify signed gems, but allow the installation of unsigned dependencies.

This is necessary because not all of `snaky_hash`’s dependencies are signed, so we cannot use `HighSecurity`.

If you want to up your security game full-time:

    bundle config set --global trust-policy MediumSecurity

NOTE: Be prepared to track down certs for signed gems and add them the same way you added mine.

## 🔧 Basic Usage

    class MySnakedHash < Hashie::Mash
      include SnakyHash::Snake.new(key_type: :string) # or :symbol
    end

    snake = MySnakedHash.new(:a => "a", "b" => "b", 2 => 2, "VeryFineHat" => "Feathers")
    snake.a # => 'a'
    snake.b # => 'b'
    snake[2] # => 2
    snake["2"] # => nil, note that this gem only affects string / symbol keys.
    snake.very_fine_hat # => 'Feathers'
    snake[:very_fine_hat] # => 'Feathers'
    snake["very_fine_hat"] # => 'Feathers'

Note above that you can access the values via the string, or symbol.
The `key_type` determines how the key is actually stored, but the hash acts as “indifferent”.
Note also that keys which do not respond to `to_sym`, because they don’t have a natural conversion to a Symbol,
are left as-is.

### Serialization

    class MySerializedSnakedHash < Hashie::Mash
      include SnakyHash::Snake.new(
        key_type: :symbol, # default :string
        serializer: true,   # default: false
      )
    end

    snake = MySerializedSnakedHash.new(:a => "a", "b" => "b", 2 => 2, "VeryFineHat" => "Feathers") # => {a: "a", b: "b", 2 => 2, very_fine_hat: "Feathers"}
    dump = MySerializedSnakedHash.dump(snake) # => "{\"a\":\"a\",\"b\":\"b\",\"2\":2,\"very_fine_hat\":\"Feathers\"}"
    hydrated = MySerializedSnakedHash.load(dump) # => {a: "a", b: "b", "2": 2, very_fine_hat: "Feathers"}
    hydrated.class # => MySerializedSnakedHash
    hydrated.a # => 'a'
    hydrated.b # => 'b'
    hydrated[2] # => nil # NOTE: this is the opposite of snake[2] => 2
    hydrated["2"] # => 2 # NOTE: this is the opposite of snake["2"] => nil
    hydrated.very_fine_hat # => 'Feathers'
    hydrated[:very_fine_hat] # => 'Feathers'
    hydrated["very_fine_hat"] # => 'Feathers'

Note that the key `VeryFineHat` changed to `very_fine_hat`.
That is indeed the point of this library, so not a bug.

Note that the key `2` changed to `"2"` (because JSON keys are strings).
When the JSON dump was reloaded it did not know to restore it as `2` instead of `"2"`.
This is also not a bug, though if you need different behavior, there is a solution in the next section.

### Extensions

You can write your own arbitrary extensions:

- “Hash Load” extensions operate on the hash and nested hashes
  - use `::load_hash_extensions.add(:extension_name) { |hash| }`
  - since v2.0.2, bugs fixed in v2.0.3
- “Value Load” extensions operate on the values, and nested hashes’ values, if any
  - use `::load_value_extensions.add(:extension_name) { |value| }`
  - since v2.0.2, bugs fixed in v2.0.3
- “Hash Dump” extensions operate on the hash and nested hashes
  - use `::dump_hash_extensions.add(:extension_name) { |value| }`
  - since v2.0.3
- “Value Dump” extensions operate on the values, and nested hashes’ values, if any
  - use `::dump_value_extensions.add(:extension_name) { |value| }`
  - since v2.0.2, bugs fixed in v2.0.3

#### Example

Let’s say I want to really smash up my hash and make it more food-like.

    class MyExtSnakedHash < Hashie::Mash
      include SnakyHash::Snake.new(
        key_type: :symbol, # default :string
        serializer: true,  # default: false
      )
    end

    # We could swap all values with indexed apples (obliteraating nested data!)
    MyExtSnakedHash.dump_hash_extensions.add(:to_apple) do |value|
      num = 0
      value.transform_values do |_key|
        key = "apple-#{num}"
        num += 1
        key
      end
    end

    # And then when loading the dump we could convert the yum to pear
    MyExtSnakedHash.load_hash_extensions.add(:apple_to_pear) do |value|
      value.transform_keys do |key|
        key.to_s.sub("yum", "pear")
      end
    end

    # We could swap all index numbers "beet-<number>"
    MyExtSnakedHash.dump_value_extensions.add(:to_beet) do |value|
      value.to_s.sub(/(\d+)/) { |match| "beet-#{match[0]}" }
    end

    # And then when loading the dump we could convert beet to corn
    MyExtSnakedHash.load_value_extensions.add(:beet_to_corn) do |value|
      value.to_s.sub("beet", "corn")
    end

    snake = MyExtSnakedHash.new({"YumBread" => "b", "YumCake" => {"b" => "b"}, "YumBoba" => [1, 2, 3]})
    snake # => {yum_bread: "b", yum_cake: {b: "b"}, yum_boba: [1, 2, 3]}
    snake.yum_bread # => "b"
    snake.yum_cake # => {b: "b"}
    snake.yum_boba # => [1, 2, 3]
    dump = snake.dump
    dump # => "{\"yum_bread\":\"apple-beet-0\",\"yum_cake\":\"apple-beet-1\",\"yum_boba\":\"apple-beet-2\"}"
    hydrated = MyExtSnakedHash.load(dump)
    hydrated # => {pear_bread: "apple-corn-0", pear_cake: "apple-corn-1", pear_boba: "apple-corn-2"}

See the specs for more examples.

### Bad Ideas

I don’t recommend using these features… but they exist (for now).

Show me what I should *not* do!
You can still access the original un-snaked camel keys. And through them you can even use un-snaked camel methods. But don't. ```ruby snake = SnakyHash::StringKeyed["VeryFineHat" => "Feathers"] snake.key?("VeryFineHat") # => true snake["VeryFineHat"] # => 'Feathers' snake.VeryFineHat # => 'Feathers', PLEASE don't do this!!! snake["VeryFineHat"] = "pop" # Please don't do this... you'll get a warning, and it works (for now), but no guarantees. # WARN -- : You are setting a key that conflicts with a built-in method MySnakedHash#VeryFineHat defined in MySnakedHash. This can cause unexpected behavior when accessing the key as a property. You can still access the key via the #[] method. # => "pop" ``` Since you are reading this, here's what to do instead. ```ruby snake.very_fine_hat = "pop" # => 'pop', do this instead!!! snake.very_fine_hat # => 'pop' snake[:very_fine_hat] = "moose" # => 'moose', or do this instead!!! snake.very_fine_hat # => 'moose' snake["very_fine_hat"] = "cheese" # => 'cheese', or do this instead!!! snake.very_fine_hat # => 'cheese' ```

### 🚀 Release Instructions

See CONTRIBUTING.md.

## 🔐 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

### 🪇 Code of Conduct

Everyone interacting with this project’s codebases, issue trackers,
chat rooms and mailing lists agrees to follow the .

## 🌈 Contributors

Made with contributors-img.

Also see GitLab Contributors: https://gitlab.com/oauth-xx/snaky_hash/-/graphs/main

## ⭐️ Star History

</a>

## 📌 Versioning

This Library adheres to .
Violations of this scheme should be reported as bugs.
Specifically, if a minor or patch version is released that breaks backward compatibility,
a new version should be immediately released that restores compatibility.
Breaking changes to the public API will only be introduced with new major versions.

### 📌 Is “Platform Support” part of the public API?

Yes. But I’m obligated to include notes…

SemVer should, but doesn’t explicitly, say that dropping support for specific Platforms
is a breaking change to an API.
It is obvious to many, but not all, and since the spec is silent, the bike shedding is endless.

> dropping support for a platform is both obviously and objectively a breaking change

- Jordan Harband (@ljharb, maintainer of SemVer) in SemVer issue 716

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:

- “Major Version Numbers are Not Sacred”

As a result of this policy, and the interpretive lens used by the maintainer,
you can (and should) specify a dependency on these libraries using
the Pessimistic Version Constraint with two digits of precision.

For example:

    spec.add_dependency("snaky_hash", "~> 2.0")

See CHANGELOG.md for list of releases.

## 📄 License

The gem is available as open source under the terms of
the MIT License .
See LICENSE.txt for the official Copyright Notice.

### © Copyright

- 2022, 2025-2026 Peter H. Boling, of RailsBling.com , and snaky_hash contributors

## 🤑 One more thing

You made it to the bottom of the page,
so perhaps you’ll indulge me for another 20 seconds.
I maintain many dozens of gems, including this one,
because I want Ruby to be a great place for people to solve problems, big and small.
Please consider supporting my efforts via the giant yellow link below,
or one of the others at the head of this README.

Deprecated Badges
CodeCov currently fails to parse the coverage upload. [![CodeCov Test Coverage][🔑codecovi♻️]][🔑codecov] [![Coverage Graph][🔑codecov-g♻️]][🔑codecov]