Class: Libis::Tools::DeepStruct
- Includes:
- Enumerable
- Defined in:
- lib/libis/tools/deep_struct.rb
Overview
A class that derives from OpenStruct through the RecursiveOpenStruct. By wrapping a Hash recursively, it allows for easy access to the content by method names. A RecursiveOpenStruct is derived from stdlib’s OpenStruct, but can be made recursive. DeepStruct enforces this behaviour and adds a clear! method.
Direct Known Subclasses
Instance Method Summary collapse
-
#clear! ⇒ Object
Delete all data fields.
- #each(&block) ⇒ Object
-
#initialize(hash = {}, opts = {}) ⇒ DeepStruct
constructor
Create a new DeepStruct from a Hash and configure the behaviour.
- #key?(key) ⇒ Boolean (also: #has_key?)
- #keys ⇒ Object
- #merge(hash) ⇒ Object
- #merge!(hash) ⇒ Object
Constructor Details
#initialize(hash = {}, opts = {}) ⇒ DeepStruct
Create a new DeepStruct from a Hash and configure the behaviour.
20 21 22 23 24 25 |
# File 'lib/libis/tools/deep_struct.rb', line 20 def initialize(hash = {}, opts = {}) hash = {} unless hash opts = {} unless opts hash = {default: hash} unless hash.is_a? Hash super(hash, {recurse_over_arrays: true, preserve_original_keys: true}.merge(opts)) end |
Instance Method Details
#clear! ⇒ Object
Delete all data fields
64 65 66 67 |
# File 'lib/libis/tools/deep_struct.rb', line 64 def clear! @table.keys.each { |key| delete_field(key) } @sub_elements = {} end |
#each(&block) ⇒ Object
59 60 61 |
# File 'lib/libis/tools/deep_struct.rb', line 59 def each(&block) self.each_pair &block end |
#key?(key) ⇒ Boolean Also known as: has_key?
50 51 52 |
# File 'lib/libis/tools/deep_struct.rb', line 50 def key?(key) self.respond_to?(key) end |
#keys ⇒ Object
55 56 57 |
# File 'lib/libis/tools/deep_struct.rb', line 55 def keys @table.keys end |
#merge(hash) ⇒ Object
27 28 29 30 31 32 33 34 35 36 |
# File 'lib/libis/tools/deep_struct.rb', line 27 def merge(hash) return self unless hash.respond_to?(:to_hash) hash.to_hash.inject(self.dup) do |ds, (key, value)| ds[key] = DeepDup.new( recurse_over_arrays: @recurse_over_arrays, preserve_original_keys: @preserve_original_keys ).call(value) ds end end |
#merge!(hash) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/libis/tools/deep_struct.rb', line 38 def merge!(hash) return self unless hash.respond_to?(:to_hash) hash.to_hash.inject(self) do |ds, (key, value)| ds[key] = DeepDup.new( recurse_over_arrays: @recurse_over_arrays, preserve_original_keys: @preserve_original_keys ).call(value) ds end self end |