You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+22-6Lines changed: 22 additions & 6 deletions
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,8 @@
1
1
# Hash with Dot Access
2
2
3
-
Rails' ActiveSupport gem provides `HashWithIndifferentAccess` which allows you to access hash keys with either strings or symbols. This gem provides `HashWithDotAccess` which subclasses `HashWithIndifferentAccess` and allows you to access or set those keys using dot access (aka methods). It utilizes `method_missing` to access key data if available, and you can also set data using `keyname=`.
3
+
This gem provides a Ruby `Hash` subclass which lets you access hash values with either string or symbol keys, as well as via methods (aka dot access). It utilizes `method_missing` to access key data if available, and you can also set data using `keyname=`. Our goal is on providing good performance and if anything offering a _subset_ of standard Hash functionality (it's a non-goal to add all-new Hash-related functionality to this class).
4
+
5
+
Performance is improved over long-running processes (such as the build process of the [Bridgetown](https://www.bridgetownrb.com) framework) by automatically defining accessors on the class so that `method_missing` is only called once per key/accessor pair.
4
6
5
7
## Example
6
8
@@ -26,13 +28,17 @@ hsh[:d]
26
28
hsh["d"]
27
29
# => "Indeed!"
28
30
29
-
hsh2 = {test:"dot access"}.with_dot_access
31
+
# You can use the `as_dots` method on Hash by loading in our refinement.
32
+
33
+
usingHashWithDotAccess::Refinements
34
+
35
+
hsh2 = {test:"dot access"}.as_dots
30
36
hsh2.test
31
37
# => "dot access"
32
38
33
39
## Nested hashes work too! Pairs nicely with lonely operator: &.
34
40
35
-
nested = {a:1, b: {c:3}}.with_dot_access
41
+
nested = {a:1, b: {c:3}}.as_dots
36
42
nested.b.c
37
43
# => 3
38
44
@@ -41,7 +47,7 @@ nested&.d&.e&.f
41
47
42
48
## You can also set default return values when key is missing
43
49
44
-
hsh = {a:1, b:2}.with_dot_access
50
+
hsh = {a:1, b:2}.as_dots
45
51
hsh.default =0
46
52
hsh.a
47
53
# => 1
@@ -63,12 +69,22 @@ Then simply require `hash_with_dot_access`:
63
69
require"hash_with_dot_access"
64
70
```
65
71
72
+
> [!IMPORTANT]
73
+
> If you're upgrading from an earlier version, and you don't want to modify your code away from using `with_dot_access`, you can add a monkey-patch to `Hash`:
74
+
> ```ruby
75
+
>classHash
76
+
>defwith_dot_access
77
+
>HashWithDotAccess::Hash.new(self)
78
+
>end
79
+
>end
80
+
>```
81
+
66
82
## Caveats
67
83
68
84
As with any Ruby object which provides arbitrary data through dynamic method calls, you may encounter collisions between your key names and existing `Hash` methods. For example:
0 commit comments