hashie 3.5.7 → 5.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (85) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +281 -195
  3. data/CONTRIBUTING.md +13 -6
  4. data/LICENSE +1 -1
  5. data/README.md +320 -60
  6. data/Rakefile +2 -2
  7. data/UPGRADING.md +121 -7
  8. data/hashie.gemspec +13 -7
  9. data/lib/hashie/clash.rb +12 -1
  10. data/lib/hashie/dash.rb +56 -35
  11. data/lib/hashie/extensions/active_support/core_ext/hash.rb +14 -0
  12. data/lib/hashie/extensions/coercion.rb +26 -19
  13. data/lib/hashie/extensions/dash/indifferent_access.rb +29 -1
  14. data/lib/hashie/extensions/dash/predefined_values.rb +88 -0
  15. data/lib/hashie/extensions/dash/property_translation.rb +59 -28
  16. data/lib/hashie/extensions/deep_fetch.rb +5 -3
  17. data/lib/hashie/extensions/deep_find.rb +14 -5
  18. data/lib/hashie/extensions/deep_locate.rb +22 -8
  19. data/lib/hashie/extensions/deep_merge.rb +26 -10
  20. data/lib/hashie/extensions/ignore_undeclared.rb +4 -5
  21. data/lib/hashie/extensions/indifferent_access.rb +43 -10
  22. data/lib/hashie/extensions/key_conflict_warning.rb +55 -0
  23. data/lib/hashie/extensions/mash/define_accessors.rb +90 -0
  24. data/lib/hashie/extensions/mash/keep_original_keys.rb +4 -5
  25. data/lib/hashie/extensions/mash/permissive_respond_to.rb +61 -0
  26. data/lib/hashie/extensions/mash/safe_assignment.rb +3 -1
  27. data/lib/hashie/extensions/mash/symbolize_keys.rb +6 -6
  28. data/lib/hashie/extensions/method_access.rb +47 -14
  29. data/lib/hashie/extensions/parsers/yaml_erb_parser.rb +28 -4
  30. data/lib/hashie/extensions/ruby_version_check.rb +5 -1
  31. data/lib/hashie/extensions/strict_key_access.rb +16 -13
  32. data/lib/hashie/extensions/stringify_keys.rb +1 -1
  33. data/lib/hashie/extensions/symbolize_keys.rb +13 -2
  34. data/lib/hashie/hash.rb +18 -11
  35. data/lib/hashie/mash.rb +147 -81
  36. data/lib/hashie/railtie.rb +7 -0
  37. data/lib/hashie/rash.rb +6 -6
  38. data/lib/hashie/utils.rb +28 -0
  39. data/lib/hashie/version.rb +1 -1
  40. data/lib/hashie.rb +22 -19
  41. metadata +23 -131
  42. data/spec/hashie/array_spec.rb +0 -29
  43. data/spec/hashie/clash_spec.rb +0 -70
  44. data/spec/hashie/dash_spec.rb +0 -573
  45. data/spec/hashie/extensions/autoload_spec.rb +0 -24
  46. data/spec/hashie/extensions/coercion_spec.rb +0 -631
  47. data/spec/hashie/extensions/dash/coercion_spec.rb +0 -13
  48. data/spec/hashie/extensions/dash/indifferent_access_spec.rb +0 -84
  49. data/spec/hashie/extensions/deep_fetch_spec.rb +0 -97
  50. data/spec/hashie/extensions/deep_find_spec.rb +0 -138
  51. data/spec/hashie/extensions/deep_locate_spec.rb +0 -137
  52. data/spec/hashie/extensions/deep_merge_spec.rb +0 -70
  53. data/spec/hashie/extensions/ignore_undeclared_spec.rb +0 -47
  54. data/spec/hashie/extensions/indifferent_access_spec.rb +0 -282
  55. data/spec/hashie/extensions/indifferent_access_with_rails_hwia_spec.rb +0 -208
  56. data/spec/hashie/extensions/key_conversion_spec.rb +0 -12
  57. data/spec/hashie/extensions/mash/keep_original_keys_spec.rb +0 -46
  58. data/spec/hashie/extensions/mash/safe_assignment_spec.rb +0 -50
  59. data/spec/hashie/extensions/mash/symbolize_keys_spec.rb +0 -39
  60. data/spec/hashie/extensions/merge_initializer_spec.rb +0 -23
  61. data/spec/hashie/extensions/method_access_spec.rb +0 -188
  62. data/spec/hashie/extensions/strict_key_access_spec.rb +0 -110
  63. data/spec/hashie/extensions/stringify_keys_spec.rb +0 -124
  64. data/spec/hashie/extensions/symbolize_keys_spec.rb +0 -129
  65. data/spec/hashie/hash_spec.rb +0 -84
  66. data/spec/hashie/mash_spec.rb +0 -763
  67. data/spec/hashie/parsers/yaml_erb_parser_spec.rb +0 -46
  68. data/spec/hashie/rash_spec.rb +0 -83
  69. data/spec/hashie/trash_spec.rb +0 -268
  70. data/spec/hashie/utils_spec.rb +0 -25
  71. data/spec/hashie/version_spec.rb +0 -7
  72. data/spec/hashie_spec.rb +0 -13
  73. data/spec/integration/omniauth/app.rb +0 -11
  74. data/spec/integration/omniauth/integration_spec.rb +0 -38
  75. data/spec/integration/omniauth-oauth2/app.rb +0 -53
  76. data/spec/integration/omniauth-oauth2/integration_spec.rb +0 -26
  77. data/spec/integration/omniauth-oauth2/some_site.rb +0 -38
  78. data/spec/integration/rails/app.rb +0 -48
  79. data/spec/integration/rails/integration_spec.rb +0 -26
  80. data/spec/integration/rails-without-dependency/integration_spec.rb +0 -15
  81. data/spec/spec_helper.rb +0 -23
  82. data/spec/support/integration_specs.rb +0 -36
  83. data/spec/support/logger.rb +0 -24
  84. data/spec/support/module_context.rb +0 -11
  85. data/spec/support/ruby_version_check.rb +0 -6
data/CONTRIBUTING.md CHANGED
@@ -1,16 +1,16 @@
1
1
  Contributing to Hashie
2
2
  ======================
3
3
 
4
- Hashie is work of [many contributors](https://github.com/intridea/hashie/graphs/contributors). You're encouraged to submit [pull requests](https://github.com/intridea/hashie/pulls), [propose features and discuss issues](https://github.com/intridea/hashie/issues).
4
+ Hashie is work of [many contributors](https://github.com/hashie/hashie/graphs/contributors). You're encouraged to submit [pull requests](https://github.com/hashie/hashie/pulls), [propose features and discuss issues](https://github.com/hashie/hashie/issues).
5
5
 
6
6
  #### Fork the Project
7
7
 
8
- Fork the [project on Github](https://github.com/intridea/hashie) and check out your copy.
8
+ Fork the [project on Github](https://github.com/hashie/hashie) and check out your copy.
9
9
 
10
10
  ```
11
11
  git clone https://github.com/contributor/hashie.git
12
12
  cd hashie
13
- git remote add upstream https://github.com/intridea/hashie.git
13
+ git remote add upstream https://github.com/hashie/hashie.git
14
14
  ```
15
15
 
16
16
  #### Create a Topic Branch
@@ -23,12 +23,19 @@ git pull upstream master
23
23
  git checkout -b my-feature-branch
24
24
  ```
25
25
 
26
- #### Bundle Install and Test
26
+ #### Install dependencies
27
+
28
+ You can use the setup script to install dependencies for the gem and its integration tests.
29
+
30
+ ```
31
+ bin/setup
32
+ ```
33
+
34
+ #### Test
27
35
 
28
36
  Ensure that you can build the project and run tests.
29
37
 
30
38
  ```
31
- bundle install
32
39
  bundle exec rake
33
40
  ```
34
41
 
@@ -105,7 +112,7 @@ git push origin my-feature-branch -f
105
112
  Update the [CHANGELOG](CHANGELOG.md) with the pull request number. A typical entry looks as follows.
106
113
 
107
114
  ```
108
- * [#123](https://github.com/intridea/hashie/pull/123): Reticulated splines - [@contributor](https://github.com/contributor).
115
+ * [#123](https://github.com/hashie/hashie/pull/123): Reticulated splines - [@contributor](https://github.com/contributor).
109
116
  ```
110
117
 
111
118
  Amend your previous commit and force push the changes.
data/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2009 Intridea, Inc., and Contributors
1
+ Copyright (c) 2009-2020 Intridea, Inc., and Contributors.
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining
4
4
  a copy of this software and associated documentation files (the
data/README.md CHANGED
@@ -1,14 +1,56 @@
1
1
  # Hashie
2
2
 
3
- [![Join the chat at https://gitter.im/intridea/hashie](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/intridea/hashie?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
4
-
3
+ [![Join the chat at https://gitter.im/hashie/hashie](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/hashie/hashie?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
5
4
  [![Gem Version](http://img.shields.io/gem/v/hashie.svg)](http://badge.fury.io/rb/hashie)
6
- [![Build Status](http://img.shields.io/travis/intridea/hashie.svg)](https://travis-ci.org/intridea/hashie)
7
- [![Dependency Status](https://gemnasium.com/intridea/hashie.svg)](https://gemnasium.com/intridea/hashie)
8
- [![Code Climate](https://codeclimate.com/github/intridea/hashie.svg)](https://codeclimate.com/github/intridea/hashie)
9
- [![Coverage Status](https://codeclimate.com/github/intridea/hashie/badges/coverage.svg)](https://codeclimate.com/github/intridea/hashie)
10
-
11
- Hashie is a growing collection of tools that extend Hashes and make them more useful.
5
+ [![Build Status](https://github.com/hashie/hashie/actions/workflows/main.yml/badge.svg)](https://github.com/hashie/hashie/actions/workflows/main.yml)
6
+
7
+ [![eierlegende Wollmilchsau](./mascot.svg)](#mascot) Hashie is a growing collection of tools that extend Hashes and make them more useful.
8
+
9
+ # Table of Contents
10
+
11
+ - [Hashie](#hashie)
12
+ - [Table of Contents](#table-of-contents)
13
+ - [Installation](#installation)
14
+ - [Stable Release](#stable-release)
15
+ - [Hash Extensions](#hash-extensions)
16
+ - [Logging](#logging)
17
+ - [Coercion](#coercion)
18
+ - [Coercing Collections](#coercing-collections)
19
+ - [Coercing Hashes](#coercing-hashes)
20
+ - [Coercing Core Types](#coercing-core-types)
21
+ - [Coercion Proc](#coercion-proc)
22
+ - [A note on circular coercion](#a-note-on-circular-coercion)
23
+ - [KeyConversion](#keyconversion)
24
+ - [MergeInitializer](#mergeinitializer)
25
+ - [MethodAccess](#methodaccess)
26
+ - [MethodAccessWithOverride](#methodaccesswithoverride)
27
+ - [MethodOverridingInitializer](#methodoverridinginitializer)
28
+ - [IndifferentAccess](#indifferentaccess)
29
+ - [IgnoreUndeclared](#ignoreundeclared)
30
+ - [DeepMerge](#deepmerge)
31
+ - [DeepFetch](#deepfetch)
32
+ - [DeepFind](#deepfind)
33
+ - [DeepLocate](#deeplocate)
34
+ - [StrictKeyAccess](#strictkeyaccess)
35
+ - [Mash](#mash)
36
+ - [KeepOriginalKeys](#keeporiginalkeys)
37
+ - [PermissiveRespondTo](#permissiverespondto)
38
+ - [SafeAssignment](#safeassignment)
39
+ - [SymbolizeKeys](#symbolizekeys)
40
+ - [DefineAccessors](#defineaccessors)
41
+ - [Dash](#dash)
42
+ - [Potential Gotchas](#potential-gotchas)
43
+ - [PropertyTranslation](#propertytranslation)
44
+ - [Mash and Rails 4 Strong Parameters](#mash-and-rails-4-strong-parameters)
45
+ - [Coercion](#coercion-1)
46
+ - [PredefinedValues](#predefinedvalues)
47
+ - [Trash](#trash)
48
+ - [Clash](#clash)
49
+ - [Rash](#rash)
50
+ - [Auto-Optimized](#auto-optimized)
51
+ - [Mascot](#mascot)
52
+ - [Contributing](#contributing)
53
+ - [Copyright](#copyright)
12
54
 
13
55
  ## Installation
14
56
 
@@ -18,9 +60,9 @@ Hashie is available as a RubyGem:
18
60
  $ gem install hashie
19
61
  ```
20
62
 
21
- ## Upgrading
63
+ ## Stable Release
22
64
 
23
- You're reading the documentation for the stable release of Hashie, 3.5.7. Please read [UPGRADING](UPGRADING.md) when upgrading from a previous version.
65
+ You're reading the documentation for the stable release of Hashie, v5.0.0.
24
66
 
25
67
  ## Hash Extensions
26
68
 
@@ -133,7 +175,7 @@ You can also use coerce from the following supertypes with `coerce_value`:
133
175
  - Integer
134
176
  - Numeric
135
177
 
136
- Hashie does not have built-in support for coercion boolean values, since Ruby does not have a built-in boolean type or standard method for to a boolean. You can coerce to booleans using a custom proc.
178
+ Hashie 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.
137
179
 
138
180
  ### Coercion Proc
139
181
 
@@ -197,8 +239,8 @@ The KeyConversion extension gives you the convenience methods of `symbolize_keys
197
239
  Hashie also has a utility method for converting keys on a Hash without a mixin:
198
240
 
199
241
  ```ruby
200
- Hashie.symbolize_keys! hash # => Symbolizes keys of hash.
201
- Hashie.symbolize_keys hash # => Returns a copy of hash with keys symbolized.
242
+ Hashie.symbolize_keys! hash # => Symbolizes all string keys of hash.
243
+ Hashie.symbolize_keys hash # => Returns a copy of hash with string keys symbolized.
202
244
  Hashie.stringify_keys! hash # => Stringifies keys of hash.
203
245
  Hashie.stringify_keys hash # => Returns a copy of hash with keys stringified.
204
246
  ```
@@ -245,14 +287,32 @@ overriding.zip #=> 'a-dee-doo-dah'
245
287
  overriding.__zip #=> [[['zip', 'a-dee-doo-dah']]]
246
288
  ```
247
289
 
290
+ ### MethodOverridingInitializer
291
+
292
+ The 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`.
293
+
294
+ ```ruby
295
+ class MyHash < Hash
296
+ end
297
+
298
+ class MyOverridingHash < Hash
299
+ include Hashie::Extensions::MethodOverridingInitializer
300
+ end
301
+
302
+ non_overriding = MyHash.new(zip: 'a-dee-doo-dah')
303
+ non_overriding.zip #=> []
304
+
305
+ overriding = MyOverridingHash.new(zip: 'a-dee-doo-dah')
306
+ overriding.zip #=> 'a-dee-doo-dah'
307
+ overriding.__zip #=> [[['zip', 'a-dee-doo-dah']]]
308
+ ```
309
+
248
310
  ### IndifferentAccess
249
311
 
250
312
  This 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.
251
313
 
252
314
  In addition, IndifferentAccess will also inject itself into sub-hashes so they behave the same.
253
315
 
254
- Example:
255
-
256
316
  ```ruby
257
317
  class MyHash < Hash
258
318
  include Hashie::Extensions::MergeInitializer
@@ -272,6 +332,18 @@ myhash['fishes'][:food] = 'flakes'
272
332
  myhash['fishes']['food'] # => "flakes"
273
333
  ```
274
334
 
335
+ To get back a normal, not-indifferent Hash, you can use `#to_hash` on the indifferent hash. It exports the keys as strings, not symbols:
336
+
337
+ ```ruby
338
+ myhash = MyHash.new
339
+ myhash["foo"] = "bar"
340
+ myhash[:foo] #=> "bar"
341
+
342
+ normal_hash = myhash.to_hash
343
+ myhash["foo"] #=> "bar"
344
+ myhash[:foo] #=> nil
345
+ ```
346
+
275
347
  ### IgnoreUndeclared
276
348
 
277
349
  This 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.
@@ -298,8 +370,8 @@ p.email # => NoMethodError
298
370
 
299
371
  ### DeepMerge
300
372
 
301
- This extension allow you to easily include a recursive merging
302
- system to any Hash descendant:
373
+ This extension allows you to easily include a recursive merging
374
+ system into any Hash descendant:
303
375
 
304
376
  ```ruby
305
377
  class MyHash < Hash
@@ -427,8 +499,6 @@ books.deep_locate -> (key, value, object) { key == :pages && value <= 120 }
427
499
 
428
500
  This extension can be mixed in to allow a Hash to raise an error when attempting to extract a value using a non-existent key.
429
501
 
430
- ### Example:
431
-
432
502
  ```ruby
433
503
  class StrictKeyAccessHash < Hash
434
504
  include Hashie::Extensions::StrictKeyAccess
@@ -446,8 +516,6 @@ end
446
516
 
447
517
  Mash 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.
448
518
 
449
- ### Example:
450
-
451
519
  ```ruby
452
520
  mash = Hashie::Mash.new
453
521
  mash.name? # => false
@@ -470,9 +538,9 @@ mash.inspect # => <Hashie::Mash>
470
538
 
471
539
  **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.
472
540
 
473
- Please 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.
541
+ _How does Mash handle conflicts with pre-existing methods?_
474
542
 
475
- ### Example:
543
+ Please 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.
476
544
 
477
545
  ```ruby
478
546
  mash = Hashie::Mash.new
@@ -481,9 +549,96 @@ mash.zip = "Method Override?"
481
549
  mash.zip # => [[["name", "My Mash"]], [["zip", "Method Override?"]]]
482
550
  ```
483
551
 
484
- Mash allows you also to transform any files into a Mash objects.
552
+ Since 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:
553
+
554
+ ```ruby
555
+ Hashie.logger = Rails.logger
556
+ ```
557
+
558
+ You can also disable the logging in subclasses of Mash:
559
+
560
+ ```ruby
561
+ class Response < Hashie::Mash
562
+ disable_warnings
563
+ end
564
+ ```
565
+
566
+ The 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:
485
567
 
486
- ### Example:
568
+ ```ruby
569
+ class Response < Hashie::Mash
570
+ disable_warnings :zip, :zap
571
+ end
572
+ ```
573
+
574
+ This behavior is cumulative. The examples above and below behave identically.
575
+
576
+ ```ruby
577
+ class Response < Hashie::Mash
578
+ disable_warnings :zip
579
+ disable_warnings :zap
580
+ end
581
+ ```
582
+
583
+ Disable 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.
584
+
585
+ ```ruby
586
+ class Message < Hashie::Mash
587
+ disable_warnings :zip, :zap
588
+ disable_warnings
589
+ end
590
+
591
+ # No errors will be logged
592
+ Message.new(merge: 'true', compact: true)
593
+ ```
594
+
595
+ ```ruby
596
+ class Message < Hashie::Mash
597
+ disable_warnings
598
+ end
599
+
600
+ class Response < Message
601
+ disable_warnings :zip, :zap
602
+ end
603
+
604
+ # 2 errors will be logged
605
+ Response.new(merge: 'true', compact: true, zip: '90210', zap: 'electric')
606
+ ```
607
+
608
+ If you would like to create an anonymous subclass of a Hashie::Mash with key conflict warnings disabled:
609
+
610
+ ```ruby
611
+ Hashie::Mash.quiet.new(zip: '90210', compact: true) # no errors logged
612
+ Hashie::Mash.quiet(:zip).new(zip: '90210', compact: true) # error logged for compact
613
+ ```
614
+
615
+ _How does the wrapping of Mash sub-Hashes work?_
616
+
617
+ Mash 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.
618
+
619
+ ```ruby
620
+ mash = Hashie::Mash.new(name: "Hashie", dependencies: { rake: "< 11", rspec: "~> 3.0" })
621
+ mash.dependencies.class #=> Hashie::Mash
622
+
623
+ class MyGem < Hashie::Mash; end
624
+ my_gem = MyGem.new(name: "Hashie", dependencies: { rake: "< 11", rspec: "~> 3.0" })
625
+ my_gem.dependencies.class #=> MyGem
626
+ ```
627
+
628
+ _How does Mash handle key types which cannot be symbolized?_
629
+
630
+ Mash preserves keys which cannot be converted *directly* to both a string and a symbol, such as numeric keys. Since Mash is conceived to provide psuedo-object functionality, handling keys which cannot represent a method call falls outside its scope of value.
631
+
632
+ ```ruby
633
+ Hashie::Mash.new('1' => 'one string', :'1' => 'one sym', 1 => 'one num')
634
+ # => {"1"=>"one sym", 1=>"one num"}
635
+ ```
636
+
637
+ The 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'`.
638
+
639
+ _What else can Mash do?_
640
+
641
+ Mash allows you also to transform any files into a Mash objects.
487
642
 
488
643
  ```yml
489
644
  #/etc/config/settings/twitter.yml
@@ -515,7 +670,7 @@ Twitter.extend mash.to_module # NOTE: if you want another name than settings, ca
515
670
  Twitter.settings.api_key # => 'abcd'
516
671
  ```
517
672
 
518
- You can use another parser (by default: YamlErbParser):
673
+ You can use another parser (by default: [YamlErbParser](lib/hashie/extensions/parsers/yaml_erb_parser.rb)):
519
674
 
520
675
  ```
521
676
  #/etc/data/user.csv
@@ -531,23 +686,17 @@ mash = Mash.load('data/user.csv', parser: MyCustomCsvParser)
531
686
  mash[1] #=> { name: 'John', lastname: 'Doe' }
532
687
  ```
533
688
 
534
- Since 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:
535
-
536
- ```ruby
537
- Hashie.logger = Rails.logger
538
- ```
689
+ The `Mash#load` method calls `YAML.safe_load(path, [], [], true)`.
539
690
 
540
- You can also disable the logging in subclasses of Mash:
691
+ Specify `permitted_symbols`, `permitted_classes` and `aliases` options as needed.
541
692
 
542
693
  ```ruby
543
- class Response < Hashie::Mash
544
- disable_warnings
545
- end
694
+ Mash.load('data/user.csv', permitted_classes: [Symbol], permitted_symbols: [], aliases: false)
546
695
  ```
547
696
 
548
- ### Mash Extension: KeepOriginalKeys
697
+ ### KeepOriginalKeys
549
698
 
550
- This extension can be mixed into a Mash to keep the form of any keys passed directly into the Mash. By default, Mash converts 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.
699
+ This 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.
551
700
 
552
701
  ```ruby
553
702
  class KeepingMash < ::Hashie::Mash
@@ -564,11 +713,33 @@ mash['string_key'] #=> 'string'
564
713
  mash[:string_key] #=> 'string'
565
714
  ```
566
715
 
567
- ### Mash Extension: SafeAssignment
716
+ ### PermissiveRespondTo
568
717
 
569
- This 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.
718
+ By 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:
719
+
720
+ ```ruby
721
+ mash = Hashie::Mash.new(a: 1)
722
+ mash.respond_to? :b #=> false
723
+ ```
724
+
725
+ This 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.
726
+
727
+ In order to have a SimpleDelegator-compatible Mash, you can use the `PermissiveRespondTo` extension to make Mash respond to anything.
728
+
729
+ ```ruby
730
+ class PermissiveMash < Hashie::Mash
731
+ include Hashie::Extensions::Mash::PermissiveRespondTo
732
+ end
733
+
734
+ mash = PermissiveMash.new(a: 1)
735
+ mash.respond_to? :b #=> true
736
+ ```
737
+
738
+ This 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.
570
739
 
571
- #### Example:
740
+ ### SafeAssignment
741
+
742
+ This 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.
572
743
 
573
744
  ```ruby
574
745
  class SafeMash < ::Hashie::Mash
@@ -580,9 +751,9 @@ safe_mash.zip = 'Test' # => ArgumentError
580
751
  safe_mash[:zip] = 'test' # => still ArgumentError
581
752
  ```
582
753
 
583
- ### Mash Extension:: SymbolizeKeys
754
+ ### SymbolizeKeys
584
755
 
585
- This 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 keys to symbols.
756
+ This 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.
586
757
 
587
758
  ```ruby
588
759
  class SymbolizedMash < ::Hashie::Mash
@@ -593,6 +764,12 @@ symbol_mash = SymbolizedMash.new
593
764
  symbol_mash['test'] = 'value'
594
765
  symbol_mash.test #=> 'value'
595
766
  symbol_mash.to_h #=> {test: 'value'}
767
+
768
+ def example(test:)
769
+ puts test
770
+ end
771
+
772
+ example(symbol_mash) #=> value
596
773
  ```
597
774
 
598
775
  There 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:
@@ -607,14 +784,37 @@ end
607
784
 
608
785
  However, 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.
609
786
 
787
+ ### DefineAccessors
788
+
789
+ This 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.
790
+
791
+ ```ruby
792
+ class MyHash < ::Hashie::Mash
793
+ include Hashie::Extensions::Mash::DefineAccessors
794
+ end
795
+
796
+ mash = MyHash.new
797
+ MyHash.method_defined?(:foo=) #=> false
798
+ mash.foo = 123
799
+ MyHash.method_defined?(:foo=) #=> true
800
+
801
+ MyHash.method_defined?(:foo) #=> false
802
+ mash.foo #=> 123
803
+ MyHash.method_defined?(:foo) #=> true
804
+ ```
805
+
806
+ You can also extend the existing mash without defining a class:
807
+
808
+ ```ruby
809
+ mash = ::Hashie::Mash.new.with_accessors!
810
+ ```
811
+
610
812
  ## Dash
611
813
 
612
814
  Dash 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.
613
815
 
614
816
  You 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.
615
817
 
616
- ### Example:
617
-
618
818
  ```ruby
619
819
  class Person < Hashie::Dash
620
820
  property :name, required: true
@@ -651,8 +851,6 @@ p.occupation # => 'Rubyist'
651
851
 
652
852
  Properties defined as symbols are not the same thing as properties defined as strings.
653
853
 
654
- ### Example:
655
-
656
854
  ```ruby
657
855
  class Tricky < Hashie::Dash
658
856
  property :trick
@@ -676,13 +874,64 @@ p = Tricky.new('trick' => 'two')
676
874
  p.trick # => NoMethodError
677
875
  ```
678
876
 
679
- ### Dash Extension: PropertyTranslation
877
+ If you would like to update a Dash and use any default values set in the case of a `nil` value, use `#update_attributes!`.
878
+
879
+ ```ruby
880
+ class WithDefaults < Hashie::Dash
881
+ property :description, default: 'none'
882
+ end
883
+
884
+ dash = WithDefaults.new
885
+ dash.description #=> 'none'
886
+
887
+ dash.description = 'You committed one of the classic blunders!'
888
+ dash.description #=> 'You committed one of the classic blunders!'
889
+
890
+ dash.description = nil
891
+ dash.description #=> nil
892
+
893
+ dash.description = 'Only slightly less known is ...'
894
+ dash.update_attributes!(description: nil)
895
+ dash.description #=> 'none'
896
+ ```
897
+
898
+ ### Potential Gotchas
899
+
900
+ Because 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:
901
+
902
+ ```ruby
903
+ class Foo < Hashie::Dash
904
+ property :bar
905
+ end
906
+
907
+ foo = Foo.new(bar: 'baz') #=> {:bar=>"baz"}
908
+ qux = { **foo, quux: 'corge' } #=> {:bar=> "baz", :quux=>"corge"}
909
+ qux.is_a?(Foo) #=> true
910
+ qux[:quux]
911
+ #=> raise NoMethodError, "The property 'quux' is not defined for Foo."
912
+ qux.key?(:quux) #=> true
913
+ ```
914
+
915
+ You can work around this problem in two ways:
916
+
917
+ 1. Call `#to_h` on the resulting object to convert it into a Hash.
918
+ 2. 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.
919
+
920
+ ```ruby
921
+ qux = { **foo, quux: 'corge' }.to_h #=> {:bar=> "baz", :quux=>"corge"}
922
+ qux.is_a?(Hash) #=> true
923
+ qux[:quux] #=> "corge"
924
+
925
+ qux = { quux: 'corge', **foo } #=> {:quux=>"corge", :bar=> "baz"}
926
+ qux.is_a?(Hash) #=> true
927
+ qux[:quux] #=> "corge"
928
+ ```
929
+
930
+ ### PropertyTranslation
680
931
 
681
932
  The `Hashie::Extensions::Dash::PropertyTranslation` mixin extends a Dash with
682
933
  the ability to remap keys from a source hash.
683
934
 
684
- ### Example from inconsistent APIs
685
-
686
935
  Property translation is useful when you need to read data from another
687
936
  application -- such as a Java API -- where the keys are named differently from
688
937
  Ruby conventions.
@@ -702,8 +951,6 @@ person[:first_name] #=> 'Michael'
702
951
  person[:last_name] #=> 'Bleigh
703
952
  ```
704
953
 
705
- ### Example using translation lambdas
706
-
707
954
  You can also use a lambda to translate the value. This is particularly useful
708
955
  when you want to ensure the type of data you're wrapping.
709
956
 
@@ -716,7 +963,7 @@ class DataModelHash < Hashie::Dash
716
963
  end
717
964
 
718
965
  model = DataModelHash.new(id: '123', created: '2014-04-25 22:35:28')
719
- model.id.class #=> Fixnum
966
+ model.id.class #=> Integer (Fixnum if you are using Ruby 2.3 or lower)
720
967
  model.created_at.class #=> Time
721
968
  ```
722
969
 
@@ -724,7 +971,7 @@ model.created_at.class #=> Time
724
971
 
725
972
  To enable compatibility with Rails 4 use the [hashie-forbidden_attributes](https://github.com/Maxim-Filimonov/hashie-forbidden_attributes) gem.
726
973
 
727
- ### Dash Extension: Coercion.
974
+ ### Coercion
728
975
 
729
976
  If you want to use `Hashie::Extensions::Coercion` together with `Dash` then
730
977
  you may probably want to use `Hashie::Extensions::Dash::Coercion` instead.
@@ -754,6 +1001,20 @@ class UserHash < Hashie::Dash
754
1001
  end
755
1002
  ```
756
1003
 
1004
+ ### PredefinedValues
1005
+
1006
+ The `Hashie::Extensions::Dash::PredefinedValues` mixin extends a Dash with
1007
+ the ability to accept predefined values on a property.
1008
+
1009
+ ```ruby
1010
+ class UserHash < Hashie::Dash
1011
+ include Hashie::Extensions::Dash::PredefinedValues
1012
+
1013
+ property :gender, values: %i[male female prefer_not_to_say]
1014
+ property :age, values: (0..150)
1015
+ end
1016
+ ```
1017
+
757
1018
  ## Trash
758
1019
 
759
1020
  A Trash is a Dash that allows you to translate keys on initialization. It mixes
@@ -785,7 +1046,7 @@ this will produce the following
785
1046
 
786
1047
  ```ruby
787
1048
  result = Result.new(id: '123', creation_date: '2012-03-30 17:23:28')
788
- result.id.class # => Fixnum
1049
+ result.id.class # => Integer (Fixnum if you are using Ruby 2.3 or lower)
789
1050
  result.created_at.class # => Time
790
1051
  ```
791
1052
 
@@ -795,8 +1056,6 @@ Clash is a Chainable Lazy Hash that allows you to easily construct complex hashe
795
1056
 
796
1057
  Essentially, 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.
797
1058
 
798
- ### Example:
799
-
800
1059
  ```ruby
801
1060
  c = Hashie::Clash.new
802
1061
  c.where(abc: 'def').order(:created_at)
@@ -822,8 +1081,6 @@ A good use case for the Rash is an URL router for a web framework, where URLs ne
822
1081
 
823
1082
  If the Rash's value is a `proc`, the `proc` will be automatically called with the regexp's MatchData (matched groups) as a block argument.
824
1083
 
825
- ### Example:
826
-
827
1084
  ```ruby
828
1085
 
829
1086
  # Mapping names to appropriate greetings
@@ -840,18 +1097,21 @@ mapper["I like traffic lights"] # => "Who DOESN'T like traffic lights?!"
840
1097
  mapper["Get off my lawn!"] # => "Forget your lawn, old man!"
841
1098
  ```
842
1099
 
843
- ### Auto-optimized
1100
+ ### Auto-Optimized
844
1101
 
845
1102
  **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).
846
1103
 
847
1104
  If this value is too low or too high for your needs, you can tune it by setting: `rash.optimize_every = n`.
848
1105
 
1106
+ ## Mascot
1107
+ [![eierlegende Wollmilchsau](./mascot.svg)](https://en.wiktionary.org/wiki/eierlegende_Wollmilchsau) Meet Hashie's "offical" mascot, the [eierlegende Wollmilchsau](https://en.wiktionary.org/wiki/eierlegende_Wollmilchsau)!
1108
+
849
1109
  ## Contributing
850
1110
 
851
1111
  See [CONTRIBUTING.md](CONTRIBUTING.md)
852
1112
 
853
1113
  ## Copyright
854
1114
 
855
- Copyright (c) 2009-2014 Intridea, Inc. (http://intridea.com/) and [contributors](https://github.com/intridea/hashie/graphs/contributors).
1115
+ Copyright (c) 2009-2020 [Intridea, Inc.](http://intridea.com), and [contributors](https://github.com/hashie/hashie/graphs/contributors).
856
1116
 
857
1117
  MIT License. See [LICENSE](LICENSE) for details.
data/Rakefile CHANGED
@@ -24,9 +24,9 @@ task :integration_specs do
24
24
  run_all_integration_specs(handler: handler, logger: ->(msg) { puts msg })
25
25
 
26
26
  if status_codes.any?
27
- $stderr.puts "#{status_codes.size} integration test(s) failed"
27
+ warn "#{status_codes.size} integration test(s) failed"
28
28
  exit status_codes.last
29
29
  end
30
30
  end
31
31
 
32
- task default: [:rubocop, :spec, :integration_specs]
32
+ task default: %i[rubocop spec integration_specs]