snaky_hash

🐍 SnakyHash

Version License: MIT Downloads Rank Open Source Helpers Depfu Coveralls Test Coverage QLTY Test Coverage QLTY Maintainability CI Heads CI Runtime Dependencies @ HEAD CI Current CI Truffle Ruby CI JRuby CI Supported CI Legacy CI Unsupported CI Ancient CI Test Coverage CI Style CodeQL


Liberapay Goal Progress Sponsor Me on Github Buy me a coffee Donate on Polar Donate to my FLOSS or refugee efforts at ko-fi.com Donate to my FLOSS or refugee efforts using Patreon

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:

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 Live Chat on Discord 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:

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*.

* 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 Gem name Gem namespace
Works with JRuby JRuby 9.2 Compat JRuby 9.3 Compat JRuby 9.4 Compat JRuby 10.0 Compat JRuby HEAD Compat
Works with Truffle Ruby Truffle Ruby 23.1 Compat Truffle Ruby 24.1 Compat Truffle Ruby HEAD Compat
Works with MRI Ruby 3 Ruby 3.0 Compat Ruby 3.1 Compat Ruby 3.2 Compat Ruby 3.3 Compat Ruby 3.4 Compat Ruby HEAD Compat
Works with MRI Ruby 2 Ruby 2.3 Compat Ruby 2.4 Compat Ruby 2.5 Compat Ruby 2.6 Compat Ruby 2.7 Compat
Source Source on GitLab.com Source on CodeBerg.org Source on Github.com The best SHA: dQw4w9WgXcQ!
Documentation Discussion Current release on RubyDoc.info HEAD on RubyDoc.info BDFL Blog Wiki
Compliance License: MIT 📄ilo-declaration-img Security Policy Contributor Covenant 2.1 SemVer 2.0.0
Style Enforced Code Style Linter Keep-A-Changelog 1.0.0 Gitmoji Commits
Support Live Chat on Discord Get help from me on Upwork Get help from me on Codementor
Enterprise Support Get help from me on Tidelift
💡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 🎖️ Follow Me on LinkedIn Follow Me on Ruby.Social Follow Me on Bluesky Contact BDFL My technical writing
... 💖 Find Me on WellFound: Find Me on CrunchBase My LinkTree More About Me 🧊 🐙 🛖 🧪

✨ 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:

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 Keep A Changelog so if you make changes, remember to update it.

See CONTRIBUTING.md for more detailed instructions.

Code Coverage

Coveralls Test Coverage QLTY Test Coverage

🪇 Code of Conduct

Everyone interacting in this project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the Contributor Covenant 2.1.

🌈 Contributors

Contributors

Made with contributors-img.

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

⭐️ Star History

Star History Chart

</a>

📌 Versioning

This Library adheres to Semantic Versioning 2.0.0. 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

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:

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 License: MIT. See LICENSE.txt for the official Copyright Notice.

🤑 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.

Buy me a latte

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