Module: Valuables::DeepFreeze
- Defined in:
- lib/valuables/deep_freeze.rb
Overview
Deep freezing functionality for Ruby objects
Freeze Ruby objects like a regular #freeze would do, but also freeze any included values. This comes with support for commonly used Ruby classes, such as Hash, Array and Range.
To make custom objects work with DeepFreeze, define a #deep_freeze method.
Class Method Summary collapse
-
.deep_freeze(obj) ⇒ Object
Like Ruby’s
#freezebut recurses into contained values.
Class Method Details
.deep_freeze(obj) ⇒ Object
Like Ruby’s #freeze but recurses into contained values.
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/valuables/deep_freeze.rb', line 15 def deep_freeze(obj) case obj when ->(obj) { obj.respond_to?(:deep_freeze) } obj.deep_freeze when Hash obj.reduce({}) do |acc, (key, value)| acc.merge deep_freeze(key) => deep_freeze(value) end.freeze when Array obj.reduce([]) do |acc, value| acc << deep_freeze(value) end.freeze when Range deep_freeze(obj.begin)..deep_freeze(obj.end).freeze when Symbol, Fixnum obj else obj.dup.freeze end end |