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
51 52 53 54 |
# File 'lib/libis/tools/deep_struct.rb', line 51 def clear! @table.keys.each { |key| delete_field(key) } @sub_elements = {} end |
#each(&block) ⇒ Object
46 47 48 |
# File 'lib/libis/tools/deep_struct.rb', line 46 def each(&block) self.each_pair &block end |
#key?(key) ⇒ Boolean Also known as: has_key?
37 38 39 |
# File 'lib/libis/tools/deep_struct.rb', line 37 def key?(key) self.respond_to?(key) end |
#keys ⇒ Object
42 43 44 |
# File 'lib/libis/tools/deep_struct.rb', line 42 def keys @table.keys end |
#merge(hash) ⇒ Object
27 28 29 30 |
# 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) { |ds, (key, value)| ds[key] = value; ds } end |
#merge!(hash) ⇒ Object
32 33 34 35 |
# File 'lib/libis/tools/deep_struct.rb', line 32 def merge!(hash) return self unless hash.respond_to?(:to_hash) hash.to_hash.inject(self) { |ds, (key, value)| ds[key] = value; ds } end |