{"id":13463134,"url":"https://github.com/hashie/hashie","last_synced_at":"2025-05-13T15:02:32.014Z","repository":{"id":722678,"uuid":"370242","full_name":"hashie/hashie","owner":"hashie","description":"Hashie is a collection of classes and mixins that make Ruby hashes more powerful.","archived":false,"fork":false,"pushed_at":"2025-01-30T09:11:48.000Z","size":1283,"stargazers_count":3001,"open_issues_count":36,"forks_count":313,"subscribers_count":40,"default_branch":"master","last_synced_at":"2025-05-05T22:17:24.533Z","etag":null,"topics":["hacktoberfest","hash-extensions","ruby"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hashie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2009-11-12T14:12:00.000Z","updated_at":"2025-04-19T12:41:17.000Z","dependencies_parsed_at":"2024-05-01T08:52:40.344Z","dependency_job_id":"781504ee-b103-41b4-b303-3199f21a9e87","html_url":"https://github.com/hashie/hashie","commit_stats":{"total_commits":634,"total_committers":158,"mean_commits":4.012658227848101,"dds":0.832807570977918,"last_synced_commit":"2b3120ad4a6f54990dfec5b10f5769e3714ab1e8"},"previous_names":["intridea/hashie"],"tags_count":50,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashie%2Fhashie","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashie%2Fhashie/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashie%2Fhashie/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashie%2Fhashie/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hashie","download_url":"https://codeload.github.com/hashie/hashie/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253061392,"owners_count":21847726,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","hash-extensions","ruby"],"created_at":"2024-07-31T13:00:46.732Z","updated_at":"2025-05-13T15:02:31.960Z","avatar_url":"https://github.com/hashie.png","language":"Ruby","readme":"# Hashie\n\n[![Join the chat at https://gitter.im/hashie/hashie](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/hashie/hashie?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n[![Gem Version](http://img.shields.io/gem/v/hashie.svg)](http://badge.fury.io/rb/hashie)\n[![Build Status](https://github.com/hashie/hashie/actions/workflows/test.yml/badge.svg)](https://github.com/hashie/hashie/actions/workflows/test.yml)\n\n[![eierlegende Wollmilchsau](./mascot.svg)](#mascot) Hashie is a growing collection of tools that extend Hashes and make them more useful.\n\n# Table of Contents\n\n- [Installation](#installation)\n- [Stable Release](#stable-release)\n- [Hash Extensions](#hash-extensions)\n- [Logging](#logging)\n  - [Coercion](#coercion)\n  - [Coercing Collections](#coercing-collections)\n  - [Coercing Hashes](#coercing-hashes)\n  - [Coercing Core Types](#coercing-core-types)\n  - [Coercion Proc](#coercion-proc)\n    - [A note on circular coercion](#a-note-on-circular-coercion)\n  - [KeyConversion](#keyconversion)\n  - [MergeInitializer](#mergeinitializer)\n  - [MethodAccess](#methodaccess)\n  - [MethodAccessWithOverride](#methodaccesswithoverride)\n  - [MethodOverridingInitializer](#methodoverridinginitializer)\n  - [IndifferentAccess](#indifferentaccess)\n  - [IgnoreUndeclared](#ignoreundeclared)\n  - [DeepMerge](#deepmerge)\n  - [DeepFetch](#deepfetch)\n  - [DeepFind](#deepfind)\n  - [DeepLocate](#deeplocate)\n- [StrictKeyAccess](#strictkeyaccess)\n- [Mash](#mash)\n  - [KeepOriginalKeys](#keeporiginalkeys)\n  - [PermissiveRespondTo](#permissiverespondto)\n  - [SafeAssignment](#safeassignment)\n  - [SymbolizeKeys](#symbolizekeys)\n  - [DefineAccessors](#defineaccessors)\n- [Dash](#dash)\n  - [Potential Gotchas](#potential-gotchas)\n  - [PropertyTranslation](#propertytranslation)\n  - [Mash and Rails 4 Strong Parameters](#mash-and-rails-4-strong-parameters)\n  - [Coercion](#coercion-1)\n  - [PredefinedValues](#predefinedvalues)\n- [Trash](#trash)\n- [Clash](#clash)\n- [Rash](#rash)\n  - [Auto-Optimized](#auto-optimized)\n- [Mascot](#mascot)\n- [Contributing](#contributing)\n- [Copyright](#copyright)\n\n## Installation\n\nHashie is available as a RubyGem:\n\n```bash\n$ gem install hashie\n```\n\n## Stable Release\n\nYou're reading the documentation for the next release of Hashie, which should be 5.0.1.\nThe current stable release is [5.0.0](https://github.com/hashie/hashie/blob/v5.0.0/README.md).\n\n## Hash Extensions\n\nThe library is broken up into a number of atomically includable Hash extension modules as described below. This provides maximum flexibility for users to mix and match functionality while maintaining feature parity with earlier versions of Hashie.\n\nAny of the extensions listed below can be mixed into a class by `include`-ing `Hashie::Extensions::ExtensionName`.\n\n## Logging\n\nHashie has a built-in logger that you can override. By default, it logs to `STDOUT` but can be replaced by any `Logger` class. The logger is accessible on the Hashie module, as shown below:\n\n```ruby\n# Set the logger to the Rails logger\nHashie.logger = Rails.logger\n```\n\n### Coercion\n\nCoercions allow you to set up \"coercion rules\" based either on the key or the value type to massage data as it's being inserted into the Hash. Key coercions might be used, for example, in lightweight data modeling applications such as an API client:\n\n```ruby\nclass Tweet \u003c Hash\n  include Hashie::Extensions::Coercion\n  include Hashie::Extensions::MergeInitializer\n  coerce_key :user, User\nend\n\nuser_hash = { name: \"Bob\" }\nTweet.new(user: user_hash)\n# =\u003e automatically calls User.coerce(user_hash) or\n#    User.new(user_hash) if that isn't present.\n```\n\nValue coercions, on the other hand, will coerce values based on the type of the value being inserted. This is useful if you are trying to build a Hash-like class that is self-propagating.\n\n```ruby\nclass SpecialHash \u003c Hash\n  include Hashie::Extensions::Coercion\n  coerce_value Hash, SpecialHash\n\n  def initialize(hash = {})\n    super\n    hash.each_pair do |k,v|\n      self[k] = v\n    end\n  end\nend\n```\n\n### Coercing Collections\n\n```ruby\nclass Tweet \u003c Hash\n  include Hashie::Extensions::Coercion\n  coerce_key :mentions, Array[User]\n  coerce_key :friends, Set[User]\nend\n\nuser_hash = { name: \"Bob\" }\nmentions_hash= [user_hash, user_hash]\nfriends_hash = [user_hash]\ntweet = Tweet.new(mentions: mentions_hash, friends: friends_hash)\n# =\u003e automatically calls User.coerce(user_hash) or\n#    User.new(user_hash) if that isn't present on each element of the array\n\ntweet.mentions.map(\u0026:class) # =\u003e [User, User]\ntweet.friends.class # =\u003e Set\n```\n\n### Coercing Hashes\n\n```ruby\nclass Relation\n  def initialize(string)\n    @relation = string\n  end\nend\n\nclass Tweet \u003c Hash\n  include Hashie::Extensions::Coercion\n  coerce_key :relations, Hash[User =\u003e Relation]\nend\n\nuser_hash = { name: \"Bob\" }\nrelations_hash= { user_hash =\u003e \"father\", user_hash =\u003e \"friend\" }\ntweet = Tweet.new(relations: relations_hash)\ntweet.relations.map { |k,v| [k.class, v.class] } # =\u003e [[User, Relation], [User, Relation]]\ntweet.relations.class # =\u003e Hash\n\n# =\u003e automatically calls User.coerce(user_hash) on each key\n#    and Relation.new on each value since Relation doesn't define the `coerce` class method\n```\n\n### Coercing Core Types\n\nHashie handles coercion to the following by using standard conversion methods:\n\n| type     | method   |\n|----------|----------|\n| Integer  | `#to_i`  |\n| Float    | `#to_f`  |\n| Complex  | `#to_c`  |\n| Rational | `#to_r`  |\n| String   | `#to_s`  |\n| Symbol   | `#to_sym`|\n\n**Note**: The standard Ruby conversion methods are less strict than you may assume. For example, `:foo.to_i` raises an error but `\"foo\".to_i` returns 0.\n\nYou can also use coerce from the following supertypes with `coerce_value`:\n- Integer\n- Numeric\n\nHashie does not have built-in support for coercing boolean values, since Ruby does not have a built-in boolean type or standard method for coercing to a boolean. You can coerce to booleans using a custom proc.\n\n### Coercion Proc\n\nYou can use a custom coercion proc on either `#coerce_key` or `#coerce_value`. This is useful for coercing to booleans or other simple types without creating a new class and `coerce` method. For example:\n\n```ruby\nclass Tweet \u003c Hash\n  include Hashie::Extensions::Coercion\n  coerce_key :retweeted, -\u003e(v) do\n    case v\n    when String\n      !!(v =~ /\\A(true|t|yes|y|1)\\z/i)\n    when Numeric\n      !v.to_i.zero?\n    else\n      v == true\n    end\n  end\nend\n```\n\n#### A note on circular coercion\n\nSince `coerce_key` is a class-level method, you cannot have circular coercion without the use of a proc. For example:\n\n```ruby\nclass CategoryHash \u003c Hash\n  include Hashie::Extensions::Coercion\n  include Hashie::Extensions::MergeInitializer\n\n  coerce_key :products, Array[ProductHash]\nend\n\nclass ProductHash \u003c Hash\n  include Hashie::Extensions::Coercion\n  include Hashie::Extensions::MergeInitializer\n\n  coerce_key :categories, Array[CategoriesHash]\nend\n```\n\nThis will fail with a `NameError` for `CategoryHash::ProductHash` because `ProductHash` is not defined at the point that `coerce_key` is happening for `CategoryHash`.\n\nTo work around this, you can use a coercion proc. For example, you could do:\n\n```ruby\nclass CategoryHash \u003c Hash\n  # ...\n  coerce_key :products, -\u003e(value) do\n    return value.map { |v| ProductHash.new(v) } if value.respond_to?(:map)\n\n    ProductHash.new(value)\n  end\nend\n```\n\n### KeyConversion\n\nThe KeyConversion extension gives you the convenience methods of `symbolize_keys` and `stringify_keys` along with their bang counterparts. You can also include just stringify or just symbolize with `Hashie::Extensions::StringifyKeys` or `Hashie::Extensions::SymbolizeKeys`.\n\nHashie also has a utility method for converting keys on a Hash without a mixin:\n\n```ruby\nHashie.symbolize_keys! hash # =\u003e Symbolizes all string keys of hash.\nHashie.symbolize_keys hash # =\u003e Returns a copy of hash with string keys symbolized.\nHashie.stringify_keys! hash # =\u003e Stringifies keys of hash.\nHashie.stringify_keys hash # =\u003e Returns a copy of hash with keys stringified.\n```\n\n### MergeInitializer\n\nThe MergeInitializer extension simply makes it possible to initialize a Hash subclass with another Hash, giving you a quick short-hand.\n\n### MethodAccess\n\nThe MethodAccess extension allows you to quickly build method-based reading, writing, and querying into your Hash descendant. It can also be included as individual modules, i.e. `Hashie::Extensions::MethodReader`, `Hashie::Extensions::MethodWriter` and `Hashie::Extensions::MethodQuery`.\n\n```ruby\nclass MyHash \u003c Hash\n  include Hashie::Extensions::MethodAccess\nend\n\nh = MyHash.new\nh.abc = 'def'\nh.abc  # =\u003e 'def'\nh.abc? # =\u003e true\n```\n\n### MethodAccessWithOverride\n\nThe MethodAccessWithOverride extension is like the MethodAccess extension, except that it allows you to override Hash methods. It aliases any overridden method with two leading underscores. To include only this overriding functionality, you can include the single module `Hashie::Extensions::MethodOverridingWriter`.\n\n```ruby\nclass MyHash \u003c Hash\n  include Hashie::Extensions::MethodAccess\nend\n\nclass MyOverridingHash \u003c Hash\n  include Hashie::Extensions::MethodAccessWithOverride\nend\n\nnon_overriding = MyHash.new\nnon_overriding.zip = 'a-dee-doo-dah'\nnon_overriding.zip #=\u003e [[['zip', 'a-dee-doo-dah']]]\n\noverriding = MyOverridingHash.new\noverriding.zip = 'a-dee-doo-dah'\noverriding.zip   #=\u003e 'a-dee-doo-dah'\noverriding.__zip #=\u003e [[['zip', 'a-dee-doo-dah']]]\n```\n\n### MethodOverridingInitializer\n\nThe MethodOverridingInitializer extension will override hash methods if you pass in a normal hash to the constructor. It aliases any overridden method with two leading underscores. To include only this initializing functionality, you can include the single module `Hashie::Extensions::MethodOverridingInitializer`.\n\n```ruby\nclass MyHash \u003c Hash\nend\n\nclass MyOverridingHash \u003c Hash\n  include Hashie::Extensions::MethodOverridingInitializer\nend\n\nnon_overriding = MyHash.new(zip: 'a-dee-doo-dah')\nnon_overriding.zip #=\u003e []\n\noverriding = MyOverridingHash.new(zip: 'a-dee-doo-dah')\noverriding.zip   #=\u003e 'a-dee-doo-dah'\noverriding.__zip #=\u003e [[['zip', 'a-dee-doo-dah']]]\n```\n\n### IndifferentAccess\n\nThis extension can be mixed in to your Hash subclass to allow you to use Strings or Symbols interchangeably as keys; similar to the `params` hash in Rails.\n\nIn addition, IndifferentAccess will also inject itself into sub-hashes so they behave the same.\n\n```ruby\nclass MyHash \u003c Hash\n  include Hashie::Extensions::MergeInitializer\n  include Hashie::Extensions::IndifferentAccess\nend\n\nmyhash = MyHash.new(:cat =\u003e 'meow', 'dog' =\u003e 'woof')\nmyhash['cat'] # =\u003e \"meow\"\nmyhash[:cat]  # =\u003e \"meow\"\nmyhash[:dog]  # =\u003e \"woof\"\nmyhash['dog'] # =\u003e \"woof\"\n\n# Auto-Injecting into sub-hashes.\nmyhash['fishes'] = {}\nmyhash['fishes'].class # =\u003e Hash\nmyhash['fishes'][:food] = 'flakes'\nmyhash['fishes']['food'] # =\u003e \"flakes\"\n```\n\nTo get back a normal, not-indifferent Hash, you can use `#to_hash` on the indifferent hash. It exports the keys as strings, not symbols:\n\n```ruby\nmyhash = MyHash.new\nmyhash[\"foo\"] = \"bar\"\nmyhash[:foo]  #=\u003e \"bar\"\n\nnormal_hash = myhash.to_hash\nmyhash[\"foo\"]  #=\u003e \"bar\"\nmyhash[:foo]  #=\u003e nil\n```\n\n### IgnoreUndeclared\n\nThis extension can be mixed in to silently ignore undeclared properties on initialization instead of raising an error. This is useful when using a Trash to capture a subset of a larger hash.\n\n```ruby\nclass Person \u003c Trash\n  include Hashie::Extensions::IgnoreUndeclared\n  property :first_name\n  property :last_name\nend\n\nuser_data = {\n  first_name: 'Freddy',\n  last_name: 'Nostrils',\n  email: 'freddy@example.com'\n}\n\np = Person.new(user_data) # 'email' is silently ignored\n\np.first_name # =\u003e 'Freddy'\np.last_name  # =\u003e 'Nostrils'\np.email      # =\u003e NoMethodError\n```\n\n### DeepMerge\n\nThis extension allows you to easily include a recursive merging\nsystem into any Hash descendant:\n\n```ruby\nclass MyHash \u003c Hash\n  include Hashie::Extensions::DeepMerge\nend\n\nh1 = MyHash[{ x: { y: [4,5,6] }, z: [7,8,9] }]\nh2 = MyHash[{ x: { y: [7,8,9] }, z: \"xyz\" }]\n\nh1.deep_merge(h2) # =\u003e { x: { y: [7, 8, 9] }, z: \"xyz\" }\nh2.deep_merge(h1) # =\u003e { x: { y: [4, 5, 6] }, z: [7, 8, 9] }\n```\n\nLike with Hash#merge in the standard library, a block can be provided to merge values:\n\n```ruby\nclass MyHash \u003c Hash\n  include Hashie::Extensions::DeepMerge\nend\n\nh1 = MyHash[{ a: 100, b: 200, c: { c1: 100 } }]\nh2 = MyHash[{ b: 250, c: { c1: 200 } }]\n\nh1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val }\n# =\u003e { a: 100, b: 450, c: { c1: 300 } }\n```\n\n\n### DeepFetch\n\nThis extension can be mixed in to provide for safe and concise retrieval of deeply nested hash values. In the event that the requested key does not exist a block can be provided and its value will be returned.\n\nThough this is a hash extension, it conveniently allows for arrays to be present in the nested structure. This feature makes the extension particularly useful for working with JSON API responses.\n\n```ruby\nuser = {\n  name: { first: 'Bob', last: 'Boberts' },\n  groups: [\n    { name: 'Rubyists' },\n    { name: 'Open source enthusiasts' }\n  ]\n}\n\nuser.extend Hashie::Extensions::DeepFetch\n\nuser.deep_fetch :name, :first # =\u003e 'Bob'\nuser.deep_fetch :name, :middle # =\u003e 'KeyError: Could not fetch middle'\n\n# using a default block\nuser.deep_fetch(:name, :middle) { |key| 'default' }  # =\u003e  'default'\n\n# a nested array\nuser.deep_fetch :groups, 1, :name # =\u003e 'Open source enthusiasts'\n```\n\n### DeepFind\n\nThis extension can be mixed in to provide for concise searching for keys within a deeply nested hash.\n\nIt can also search through any Enumerable contained within the hash for objects with the specified key.\n\nNote: The searches are depth-first, so it is not guaranteed that a shallowly nested value will be found before a deeply nested value.\n\n```ruby\nuser = {\n  name: { first: 'Bob', last: 'Boberts' },\n  groups: [\n    { name: 'Rubyists' },\n    { name: 'Open source enthusiasts' }\n  ]\n}\n\nuser.extend Hashie::Extensions::DeepFind\n\nuser.deep_find(:name)   #=\u003e { first: 'Bob', last: 'Boberts' }\nuser.deep_detect(:name) #=\u003e { first: 'Bob', last: 'Boberts' }\n\nuser.deep_find_all(:name) #=\u003e [{ first: 'Bob', last: 'Boberts' }, 'Rubyists', 'Open source enthusiasts']\nuser.deep_select(:name)   #=\u003e [{ first: 'Bob', last: 'Boberts' }, 'Rubyists', 'Open source enthusiasts']\n```\n\n### DeepLocate\n\nThis extension can be mixed in to provide a depth first search based search for enumerables matching a given comparator callable.\n\nIt returns all enumerables which contain at least one element, for which the given comparator returns ```true```.\n\nBecause the container objects are returned, the result elements can be modified in place. This way, one can perform modifications on deeply nested hashes without the need to know the exact paths.\n\n```ruby\n\nbooks = [\n  {\n    title: \"Ruby for beginners\",\n    pages: 120\n  },\n  {\n    title: \"CSS for intermediates\",\n    pages: 80\n  },\n  {\n    title: \"Collection of ruby books\",\n    books: [\n      {\n        title: \"Ruby for the rest of us\",\n        pages: 576\n      }\n    ]\n  }\n]\n\nbooks.extend(Hashie::Extensions::DeepLocate)\n\n# for ruby 1.9 leave *no* space between the lambda rocket and the braces\n# http://ruby-journal.com/becareful-with-space-in-lambda-hash-rocket-syntax-between-ruby-1-dot-9-and-2-dot-0/\n\nbooks.deep_locate -\u003e (key, value, object) { key == :title \u0026\u0026 value.include?(\"Ruby\") }\n# =\u003e [{:title=\u003e\"Ruby for beginners\", :pages=\u003e120}, {:title=\u003e\"Ruby for the rest of us\", :pages=\u003e576}]\n\nbooks.deep_locate -\u003e (key, value, object) { key == :pages \u0026\u0026 value \u003c= 120 }\n# =\u003e [{:title=\u003e\"Ruby for beginners\", :pages=\u003e120}, {:title=\u003e\"CSS for intermediates\", :pages=\u003e80}]\n```\n\n## StrictKeyAccess\n\nThis extension can be mixed in to allow a Hash to raise an error when attempting to extract a value using a non-existent key.\n\n```ruby\nclass StrictKeyAccessHash \u003c Hash\n  include Hashie::Extensions::StrictKeyAccess\nend\n\n\u003e\u003e hash = StrictKeyAccessHash[foo: \"bar\"]\n=\u003e {:foo=\u003e\"bar\"}\n\u003e\u003e hash[:foo]\n=\u003e \"bar\"\n\u003e\u003e hash[:cow]\n  KeyError: key not found: :cow\n```\n\n## Mash\n\nMash is an extended Hash that gives simple pseudo-object functionality that can be built from hashes and easily extended. It is intended to give the user easier access to the objects within the Mash through a property-like syntax, while still retaining all Hash functionality.\n\n```ruby\nmash = Hashie::Mash.new\nmash.name? # =\u003e false\nmash.name # =\u003e nil\nmash.name = \"My Mash\"\nmash.name # =\u003e \"My Mash\"\nmash.name? # =\u003e true\nmash.inspect # =\u003e \u003cHashie::Mash name=\"My Mash\"\u003e\n\nmash = Hashie::Mash.new\n# use bang methods for multi-level assignment\nmash.author!.name = \"Michael Bleigh\"\nmash.author # =\u003e \u003cHashie::Mash name=\"Michael Bleigh\"\u003e\n\nmash = Hashie::Mash.new\n# use under-bang methods for multi-level testing\nmash.author_.name? # =\u003e false\nmash.inspect # =\u003e \u003cHashie::Mash\u003e\n```\n\n**Note:** The `?` method will return false if a key has been set to false or nil. In order to check if a key has been set at all, use the `mash.key?('some_key')` method instead.\n\n_How does Mash handle conflicts with pre-existing methods?_\n\nPlease note that a Mash will not override methods through the use of the property-like syntax. This can lead to confusion if you expect to be able to access a Mash value through the property-like syntax for a key that conflicts with a method name. However, it protects users of your library from the unexpected behavior of those methods being overridden behind the scenes.\n\n```ruby\nmash = Hashie::Mash.new\nmash.name = \"My Mash\"\nmash.zip = \"Method Override?\"\nmash.zip # =\u003e [[[\"name\", \"My Mash\"]], [[\"zip\", \"Method Override?\"]]]\n```\n\nSince Mash gives you the ability to set arbitrary keys that then act as methods, Hashie logs when there is a conflict between a key and a pre-existing method. You can set the logger that this logs message to via the global Hashie logger:\n\n```ruby\nHashie.logger = Rails.logger\n```\n\nYou can also disable the logging in subclasses of Mash:\n\n```ruby\nclass Response \u003c Hashie::Mash\n  disable_warnings\nend\n```\n\nThe default is to disable logging for all methods that conflict. If you would like to only disable the logging for specific methods, you can include an array of method keys:\n\n```ruby\nclass Response \u003c Hashie::Mash\n  disable_warnings :zip, :zap\nend\n```\n\nThis behavior is cumulative. The examples above and below behave identically.\n\n```ruby\nclass Response \u003c Hashie::Mash\n  disable_warnings :zip\n  disable_warnings :zap\nend\n```\n\nDisable warnings will honor the last `disable_warnings` call. Calling without parameters will override the ignored methods list, and calling with parameters will create a new ignored methods list. This includes child classes that inherit from a class that disables warnings.\n\n```ruby\nclass Message \u003c Hashie::Mash\n  disable_warnings :zip, :zap\n  disable_warnings\nend\n\n# No errors will be logged\nMessage.new(merge: 'true', compact: true)\n```\n\n```ruby\nclass Message \u003c Hashie::Mash\n  disable_warnings\nend\n\nclass Response \u003c Message\n  disable_warnings :zip, :zap\nend\n\n# 2 errors will be logged\nResponse.new(merge: 'true', compact: true, zip: '90210', zap: 'electric')\n```\n\nIf you would like to create an anonymous subclass of a Hashie::Mash with key conflict warnings disabled:\n\n```ruby\nHashie::Mash.quiet.new(zip: '90210', compact: true) # no errors logged\nHashie::Mash.quiet(:zip).new(zip: '90210', compact: true) # error logged for compact\n```\n\n_How does the wrapping of Mash sub-Hashes work?_\n\nMash duplicates any sub-Hashes that you add to it and wraps them in a Mash. This allows for infinite chaining of nested Hashes within a Mash without modifying the object(s) that are passed into the Mash. When you subclass Mash, the subclass wraps any sub-Hashes in its own class. This preserves any extensions that you mixed into the Mash subclass and allows them to work within the sub-Hashes, in addition to the main containing Mash.\n\n```ruby\nmash = Hashie::Mash.new(name: \"Hashie\", dependencies: { rake: \"\u003c 11\", rspec: \"~\u003e 3.0\" })\nmash.dependencies.class #=\u003e Hashie::Mash\n\nclass MyGem \u003c Hashie::Mash; end\nmy_gem = MyGem.new(name: \"Hashie\", dependencies: { rake: \"\u003c 11\", rspec: \"~\u003e 3.0\" })\nmy_gem.dependencies.class #=\u003e MyGem\n```\n\n_How does Mash handle key types which cannot be symbolized?_\n\nMash preserves keys which cannot be converted *directly* to both a string and a symbol, such as numeric keys. Since Mash is conceived to provide pseudo-object functionality, handling keys which cannot represent a method call falls outside its scope of value.\n\n```ruby\nHashie::Mash.new('1' =\u003e 'one string', :'1' =\u003e 'one sym', 1 =\u003e 'one num')\n# =\u003e {\"1\"=\u003e\"one sym\", 1=\u003e\"one num\"}\n```\n\nThe symbol key `:'1'` is converted the string `'1'` to support indifferent access and consequently its value `'one sym'` will override the previously set `'one string'`. However, the subsequent key of `1` cannot directly convert to a symbol and therefore **not** converted to the string `'1'` that would otherwise override the previously set value of `'one sym'`.\n\n_What else can Mash do?_\n\nMash allows you also to transform any files into a Mash objects.\n\n```yml\n#/etc/config/settings/twitter.yml\ndevelopment:\n  api_key: 'api_key'\nproduction:\n  api_key: \u003c%= ENV['API_KEY'] %\u003e #let's say that ENV['API_KEY'] is set to 'abcd'\n```\n\n```ruby\nmash = Mash.load('settings/twitter.yml')\nmash.development.api_key # =\u003e 'localhost'\nmash.development.api_key = \"foo\" # =\u003e \u003c# RuntimeError can't modify frozen ...\u003e\nmash.development.api_key? # =\u003e true\n```\n\nYou can also load with a `Pathname` object:\n\n```ruby\nmash = Mash.load(Pathname 'settings/twitter.yml')\nmash.development.api_key # =\u003e 'localhost'\n```\n\nYou can access a Mash from another class:\n\n```ruby\nmash = Mash.load('settings/twitter.yml')[ENV['RACK_ENV']]\nTwitter.extend mash.to_module # NOTE: if you want another name than settings, call: to_module('my_settings')\nTwitter.settings.api_key # =\u003e 'abcd'\n```\n\nYou can use another parser (by default: [YamlErbParser](lib/hashie/extensions/parsers/yaml_erb_parser.rb)):\n\n```\n#/etc/data/user.csv\nid | name          | lastname\n---|------------- | -------------\n1  |John          | Doe\n2  |Laurent       | Garnier\n```\n\n```ruby\nmash = Mash.load('data/user.csv', parser: MyCustomCsvParser)\n# =\u003e { 1 =\u003e { name: 'John', lastname: 'Doe'}, 2 =\u003e { name: 'Laurent', lastname: 'Garnier' } }\nmash[1] #=\u003e { name: 'John', lastname: 'Doe' }\n```\n\nThe `Mash#load` method calls `YAML.safe_load(path, [], [], true)`.\n\nSpecify `permitted_symbols`, `permitted_classes` and `aliases` options as needed.\n\n```ruby\nMash.load('data/user.csv', permitted_classes: [Symbol], permitted_symbols: [], aliases: false)\n```\n\n### KeepOriginalKeys\n\nThis extension can be mixed into a Mash to keep the form of any keys passed directly into the Mash. By default, Mash converts symbol keys to strings to give indifferent access. This extension still allows indifferent access, but keeps the form of the keys to eliminate confusion when you're not expecting the keys to change.\n\n```ruby\nclass KeepingMash \u003c ::Hashie::Mash\n  include Hashie::Extensions::Mash::KeepOriginalKeys\nend\n\nmash = KeepingMash.new(:symbol_key =\u003e :symbol, 'string_key' =\u003e 'string')\nmash.to_hash == { :symbol_key =\u003e :symbol, 'string_key' =\u003e 'string' }  #=\u003e true\nmash.symbol_key  #=\u003e :symbol\nmash[:symbol_key]  #=\u003e :symbol\nmash['symbol_key']  #=\u003e :symbol\nmash.string_key  #=\u003e 'string'\nmash['string_key']  #=\u003e 'string'\nmash[:string_key]  #=\u003e 'string'\n```\n\n### PermissiveRespondTo\n\nBy default, Mash only states that it responds to built-in methods, affixed methods (e.g. setters, underbangs, etc.), and keys that it currently contains. That means it won't state that it responds to a getter for an unset key, as in the following example:\n\n```ruby\nmash = Hashie::Mash.new(a: 1)\nmash.respond_to? :b  #=\u003e false\n```\n\nThis means that by default Mash is not a perfect match for use with a SimpleDelegator since the delegator will not forward messages for unset keys to the Mash even though it can handle them.\n\nIn order to have a SimpleDelegator-compatible Mash, you can use the `PermissiveRespondTo` extension to make Mash respond to anything.\n\n```ruby\nclass PermissiveMash \u003c Hashie::Mash\n  include Hashie::Extensions::Mash::PermissiveRespondTo\nend\n\nmash = PermissiveMash.new(a: 1)\nmash.respond_to? :b  #=\u003e true\n```\n\nThis comes at the cost of approximately 20% performance for initialization and setters and 19KB of permanent memory growth for each such class that you create.\n\n### SafeAssignment\n\nThis extension can be mixed into a Mash to guard the attempted overwriting of methods by property setters. When mixed in, the Mash will raise an `ArgumentError` if you attempt to write a property with the same name as an existing method.\n\n```ruby\nclass SafeMash \u003c ::Hashie::Mash\n  include Hashie::Extensions::Mash::SafeAssignment\nend\n\nsafe_mash = SafeMash.new\nsafe_mash.zip   = 'Test' # =\u003e ArgumentError\nsafe_mash[:zip] = 'test' # =\u003e still ArgumentError\n```\n\n### SymbolizeKeys\n\nThis extension can be mixed into a Mash to change the default behavior of converting keys to strings. After mixing this extension into a Mash, the Mash will convert all string keys to symbols. It can be useful to use with keywords argument, which required symbol keys.\n\n```ruby\nclass SymbolizedMash \u003c ::Hashie::Mash\n  include Hashie::Extensions::Mash::SymbolizeKeys\nend\n\nsymbol_mash = SymbolizedMash.new\nsymbol_mash['test'] = 'value'\nsymbol_mash.test  #=\u003e 'value'\nsymbol_mash.to_h  #=\u003e {test: 'value'}\n\ndef example(test:)\n  puts test\nend\n\nexample(symbol_mash) #=\u003e value\n```\n\nThere is a major benefit and coupled with a major trade-off to this decision (at least on older Rubies). As a benefit, by using symbols as keys, you will be able to use the implicit conversion of a Mash via the `#to_hash` method to destructure (or splat) the contents of a Mash out to a block. This can be handy for doing iterations through the Mash's keys and values, as follows:\n\n```ruby\nsymbol_mash = SymbolizedMash.new(id: 123, name: 'Rey')\nsymbol_mash.each do |key, value|\n  # key is :id, then :name\n  # value is 123, then 'Rey'\nend\n```\n\nHowever, on Rubies less than 2.0, this means that every key you send to the Mash will generate a symbol. Since symbols are not garbage-collected on older versions of Ruby, this can cause a slow memory leak when using a symbolized Mash with data generated from user input.\n\n### DefineAccessors\n\nThis extension can be mixed into a Mash so it makes it behave like `OpenStruct`. It reduces the overhead of `method_missing?` magic by lazily defining field accessors when they're requested.\n\n```ruby\nclass MyHash \u003c ::Hashie::Mash\n  include Hashie::Extensions::Mash::DefineAccessors\nend\n\nmash = MyHash.new\nMyHash.method_defined?(:foo=) #=\u003e false\nmash.foo = 123\nMyHash.method_defined?(:foo=) #=\u003e true\n\nMyHash.method_defined?(:foo) #=\u003e false\nmash.foo #=\u003e 123\nMyHash.method_defined?(:foo) #=\u003e true\n```\n\nYou can also extend the existing mash without defining a class:\n\n```ruby\nmash = ::Hashie::Mash.new.with_accessors!\n```\n\n## Dash\n\nDash is an extended Hash that has a discrete set of defined properties and only those properties may be set on the hash. Additionally, you can set defaults for each property. You can also flag a property as required. Required properties will raise an exception if unset. Another option is message for required properties, which allow you to add custom messages for required property. A property with a proc value will be evaluated lazily upon retrieval.\n\nYou can also conditionally require certain properties by passing a Proc or Symbol. If a Proc is provided, it will be run in the context of the Dash instance. If a Symbol is provided, the value returned for the property or method of the same name will be evaluated. The property will be required if the result of the conditional is truthy.\n\n```ruby\nclass Person \u003c Hashie::Dash\n  property :name, required: true\n  property :age, required: true, message: 'must be set.'\n  property :email\n  property :phone, required: -\u003e { email.nil? }, message: 'is required if email is not set.'\n  property :pants, required: :weekday?, message: 'are only required on weekdays.'\n  property :occupation, default: 'Rubyist'\n  property :genome\n\n  def weekday?\n    [ Time.now.saturday?, Time.now.sunday? ].none?\n  end\nend\n\np = Person.new # =\u003e ArgumentError: The property 'name' is required for this Dash.\np = Person.new(name: 'Bob') # =\u003e ArgumentError: The property 'age' must be set.\n\np = Person.new(name: \"Bob\", age: 18)\np.name         # =\u003e 'Bob'\np.name = nil   # =\u003e ArgumentError: The property 'name' is required for this Dash.\np.age          # =\u003e 18\np.age = nil    # =\u003e ArgumentError: The property 'age' must be set.\np.email = 'abc@def.com'\np.occupation   # =\u003e 'Rubyist'\np.email        # =\u003e 'abc@def.com'\np[:awesome]    # =\u003e NoMethodError\np[:occupation] # =\u003e 'Rubyist'\np.update_attributes!(name: 'Trudy', occupation: 'Evil')\np.occupation   # =\u003e 'Evil'\np.name         # =\u003e 'Trudy'\np.update_attributes!(occupation: nil)\np.occupation   # =\u003e 'Rubyist'\np.genome = -\u003e { Genome.sequence } # Some expensive operation\np.genome       # =\u003e 'GATTACA'\n```\n\nProperties defined as symbols are not the same thing as properties defined as strings.\n\n```ruby\nclass Tricky \u003c Hashie::Dash\n  property :trick\n  property 'trick'\nend\n\np = Tricky.new(trick: 'one', 'trick' =\u003e 'two')\np.trick # =\u003e 'one', always symbol version\np[:trick] # =\u003e 'one'\np['trick'] # =\u003e 'two'\n```\n\nNote that accessing a property as a method always uses the symbol version.\n\n```ruby\nclass Tricky \u003c Hashie::Dash\n  property 'trick'\nend\n\np = Tricky.new('trick' =\u003e 'two')\np.trick # =\u003e NoMethodError\n```\n\nIf you would like to update a Dash and use any default values set in the case of a `nil` value, use `#update_attributes!`.\n\n```ruby\nclass WithDefaults \u003c Hashie::Dash\n  property :description, default: 'none'\nend\n\ndash = WithDefaults.new\ndash.description  #=\u003e 'none'\n\ndash.description = 'You committed one of the classic blunders!'\ndash.description  #=\u003e 'You committed one of the classic blunders!'\n\ndash.description = nil\ndash.description  #=\u003e nil\n\ndash.description = 'Only slightly less known is ...'\ndash.update_attributes!(description: nil)\ndash.description  #=\u003e 'none'\n```\n\n### Potential Gotchas\n\nBecause Dashes are subclasses of the built-in Ruby Hash class, the double-splat operator takes the Dash as-is without any conversion. This can lead to strange behavior when you use the double-splat operator on a Dash as the first part of a keyword list or built Hash. For example:\n\n```ruby\nclass Foo \u003c Hashie::Dash\n  property :bar\nend\n\nfoo = Foo.new(bar: 'baz')      #=\u003e {:bar=\u003e\"baz\"}\nqux = { **foo, quux: 'corge' } #=\u003e {:bar=\u003e \"baz\", :quux=\u003e\"corge\"}\nqux.is_a?(Foo)                 #=\u003e true\nqux[:quux]\n#=\u003e raise NoMethodError, \"The property 'quux' is not defined for Foo.\"\nqux.key?(:quux) #=\u003e true\n```\n\nYou can work around this problem in two ways:\n\n1. Call `#to_h` on the resulting object to convert it into a Hash.\n2. Use the double-splat operator on the Dash as the last argument in the Hash literal. This will cause the resulting object to be a Hash instead of a Dash, thereby circumventing the problem.\n\n```ruby\nqux = { **foo, quux: 'corge' }.to_h #=\u003e {:bar=\u003e \"baz\", :quux=\u003e\"corge\"}\nqux.is_a?(Hash)                     #=\u003e true\nqux[:quux]                          #=\u003e \"corge\"\n\nqux = { quux: 'corge', **foo } #=\u003e {:quux=\u003e\"corge\", :bar=\u003e \"baz\"}\nqux.is_a?(Hash)                #=\u003e true\nqux[:quux]                     #=\u003e \"corge\"\n```\n\n### PropertyTranslation\n\nThe `Hashie::Extensions::Dash::PropertyTranslation` mixin extends a Dash with\nthe ability to remap keys from a source hash.\n\nProperty translation is useful when you need to read data from another\napplication -- such as a Java API -- where the keys are named differently from\nRuby conventions.\n\n```ruby\nclass PersonHash \u003c Hashie::Dash\n  include Hashie::Extensions::Dash::PropertyTranslation\n\n  property :first_name, from: :firstName\n  property :last_name, from: :lastName\n  property :first_name, from: :f_name\n  property :last_name, from: :l_name\nend\n\nperson = PersonHash.new(firstName: 'Michael', l_name: 'Bleigh')\nperson[:first_name]  #=\u003e 'Michael'\nperson[:last_name]   #=\u003e 'Bleigh\n```\n\nYou can also use a lambda to translate the value. This is particularly useful\nwhen you want to ensure the type of data you're wrapping.\n\n```ruby\nclass DataModelHash \u003c Hashie::Dash\n  include Hashie::Extensions::Dash::PropertyTranslation\n\n  property :id, transform_with: -\u003e(value) { value.to_i }\n  property :created_at, from: :created, with: -\u003e(value) { Time.parse(value) }\nend\n\nmodel = DataModelHash.new(id: '123', created: '2014-04-25 22:35:28')\nmodel.id.class          #=\u003e Integer (Fixnum if you are using Ruby 2.3 or lower)\nmodel.created_at.class  #=\u003e Time\n```\n\n### Mash and Rails 4 Strong Parameters\n\nTo enable compatibility with Rails 4 use the [hashie-forbidden_attributes](https://github.com/Maxim-Filimonov/hashie-forbidden_attributes) gem.\n\n### Coercion\n\nIf you want to use `Hashie::Extensions::Coercion` together with `Dash` then\nyou may probably want to use `Hashie::Extensions::Dash::Coercion` instead.\nThis extension automatically includes `Hashie::Extensions::Coercion`\nand also adds a convenient `:coerce` option to `property` so you can define coercion in one line\ninstead of using `property` and `coerce_key` separate:\n\n```ruby\nclass UserHash \u003c Hashie::Dash\n  include Hashie::Extensions::Coercion\n\n  property :id\n  property :posts\n\n  coerce_key :posts, Array[PostHash]\nend\n```\n\nThis is the same as:\n\n```ruby\nclass UserHash \u003c Hashie::Dash\n  include Hashie::Extensions::Dash::Coercion\n\n  property :id\n  property :posts, coerce: Array[PostHash]\nend\n```\n\n### PredefinedValues\n\nThe `Hashie::Extensions::Dash::PredefinedValues` mixin extends a Dash with\nthe ability to accept predefined values on a property.\n\n```ruby\nclass UserHash \u003c Hashie::Dash\n  include Hashie::Extensions::Dash::PredefinedValues\n\n  property :gender, values: %i[male female prefer_not_to_say]\n  property :age, values: (0..150)\nend\n```\n\n## Trash\n\nA Trash is a Dash that allows you to translate keys on initialization. It mixes\nin the PropertyTranslation mixin by default and is used like so:\n\n```ruby\nclass Person \u003c Hashie::Trash\n  property :first_name, from: :firstName\nend\n```\n\nThis will automatically translate the \u003ctt\u003efirstName\u003c/tt\u003e key to \u003ctt\u003efirst_name\u003c/tt\u003e\nwhen it is initialized using a hash such as through:\n\n```ruby\nPerson.new(firstName: 'Bob')\n```\n\nTrash also supports translations using lambda, this could be useful when dealing with external API's. You can use it in this way:\n\n```ruby\nclass Result \u003c Hashie::Trash\n  property :id, transform_with: lambda { |v| v.to_i }\n  property :created_at, from: :creation_date, with: lambda { |v| Time.parse(v) }\nend\n```\n\nthis will produce the following\n\n```ruby\nresult = Result.new(id: '123', creation_date: '2012-03-30 17:23:28')\nresult.id.class         # =\u003e Integer (Fixnum if you are using Ruby 2.3 or lower)\nresult.created_at.class # =\u003e Time\n```\n\n## Clash\n\nClash is a Chainable Lazy Hash that allows you to easily construct complex hashes using method notation chaining. This will allow you to use a more action-oriented approach to building options hashes.\n\nEssentially, a Clash is a generalized way to provide much of the same kind of \"chainability\" that libraries like Arel or Rails 2.x's named_scopes provide.\n\n```ruby\nc = Hashie::Clash.new\nc.where(abc: 'def').order(:created_at)\nc # =\u003e { where: { abc: 'def' }, order: :created_at }\n\n# You can also use bang notation to chain into sub-hashes,\n# jumping back up the chain with _end!\nc = Hashie::Clash.new\nc.where!.abc('def').ghi(123)._end!.order(:created_at)\nc # =\u003e { where: { abc: 'def', ghi: 123 }, order: :created_at }\n\n# Multiple hashes are merged automatically\nc = Hashie::Clash.new\nc.where(abc: 'def').where(hgi: 123)\nc # =\u003e { where: { abc: 'def', hgi: 123 } }\n```\n\n## Rash\n\nRash is a Hash whose keys can be Regexps or Ranges, which will map many input keys to a value.\n\nA good use case for the Rash is an URL router for a web framework, where URLs need to be mapped to actions; the Rash's keys match URL patterns, while the values call the action which handles the URL.\n\nIf the Rash's value is a `proc`, the `proc` will be automatically called with the regexp's MatchData (matched groups) as a block argument.\n\n```ruby\n\n# Mapping names to appropriate greetings\ngreeting = Hashie::Rash.new( /^Mr./ =\u003e \"Hello sir!\", /^Mrs./ =\u003e \"Evening, madame.\" )\ngreeting[\"Mr. Steve Austin\"] # =\u003e \"Hello sir!\"\ngreeting[\"Mrs. Steve Austin\"] # =\u003e \"Evening, madame.\"\n\n# Mapping statements to saucy retorts\nmapper = Hashie::Rash.new(\n  /I like (.+)/ =\u003e proc { |m| \"Who DOESN'T like #{m[1]}?!\" },\n  /Get off my (.+)!/ =\u003e proc { |m| \"Forget your #{m[1]}, old man!\" }\n)\nmapper[\"I like traffic lights\"] # =\u003e \"Who DOESN'T like traffic lights?!\"\nmapper[\"Get off my lawn!\"]      # =\u003e \"Forget your lawn, old man!\"\n```\n\n### Auto-Optimized\n\n**Note:** The Rash is automatically optimized every 500 accesses (which means that it sorts the list of Regexps, putting the most frequently matched ones at the beginning).\n\nIf this value is too low or too high for your needs, you can tune it by setting: `rash.optimize_every = n`.\n\n## Mascot\n[![eierlegende Wollmilchsau](./mascot.svg)](https://en.wiktionary.org/wiki/eierlegende_Wollmilchsau) Meet Hashie's \"official\" mascot, the [eierlegende Wollmilchsau](https://en.wiktionary.org/wiki/eierlegende_Wollmilchsau)!\n\n## Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md)\n\n## Copyright\n\nCopyright (c) 2009-2020 [Intridea, Inc.](http://intridea.com), and [contributors](https://github.com/hashie/hashie/graphs/contributors).\n\nMIT License. See [LICENSE](LICENSE) for details.\n","funding_links":[],"categories":["Developer Tools","Ruby"],"sub_categories":["Ruby Core Extensions"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhashie%2Fhashie","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhashie%2Fhashie","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhashie%2Fhashie/lists"}