Skip to content

Commit da37aa7

Browse files
committed
Adds conversion back to a hash with to_h and to_dot_h for enumeration.
1 parent 808651b commit da37aa7

File tree

5 files changed

+38
-2
lines changed

5 files changed

+38
-2
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Changelog
22

3+
## [2.1.0] - 2024-04-20
4+
5+
- Adds conversion back to a hash with `to_h` and `to_dot_h` for enumeration.
6+
37
## [2.0.0] - 2024-04-20
48

59
- Completely rewrite internals and remove Active Support as a dependency

Gemfile.lock

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
PATH
22
remote: .
33
specs:
4-
hash_with_dot_access (2.0.0)
4+
hash_with_dot_access (2.1.0)
55

66
GEM
77
remote: https://rubygems.org/
@@ -15,3 +15,6 @@ DEPENDENCIES
1515
bundler
1616
hash_with_dot_access!
1717
rake (~> 13.0)
18+
19+
BUNDLED WITH
20+
2.5.6

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ hsh.x
5555
# => 0
5656
```
5757

58+
You can convert a `HashWithDotAccess::Hash` back to a regular Hash with `to_h`, which even works with
59+
block enumeration. Or use `to_dot_h` as a `to_h`-like enumerator which preserves dot access.
60+
5861
## Installation
5962

6063
Add this line to your application's Gemfile:

lib/hash_with_dot_access.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,18 @@ def self.normalized_value(obj, value)
1313
value
1414
end
1515
end
16+
17+
def self.primitive_value(value)
18+
case value
19+
when ::Hash
20+
value.to_h
21+
when Array
22+
value = value.dup if value.frozen?
23+
value.map! { primitive_value(_1) }
24+
else
25+
value
26+
end
27+
end
1628
end
1729

1830
class Hash < ::Hash
@@ -138,6 +150,20 @@ def transform_values(...)
138150
def compact
139151
dup.tap { _1.compact! }
140152
end
153+
154+
alias_method :_to_h, :to_h
155+
156+
def to_dot_h(...)
157+
self.class.new _to_h(...)
158+
end
159+
160+
def to_h
161+
::Hash.new.update(self).to_h do |k, v|
162+
value = Utils.primitive_value(v)
163+
k, value = yield k, value if block_given?
164+
[k, value]
165+
end
166+
end
141167
end
142168

143169
module Refinements

lib/hash_with_dot_access/version.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module HashWithDotAccess
2-
VERSION = "2.0.0"
2+
VERSION = "2.1.0"
33
end

0 commit comments

Comments
 (0)