Class: Libis::Tools::DeepStruct

Inherits:
RecursiveOpenStruct
  • Object
show all
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

ConfigFile

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}, opts = {}) ⇒ DeepStruct

Create a new DeepStruct from a Hash and configure the behaviour.

Parameters:

  • hash (Hash) (defaults to: {})

    the initial data structure.

  • opts (Hash) (defaults to: {})

    optional configuration options:

    • recurse_over_arrays: also wrap the Hashes that are enbedded in Arrays. Default: true.

    • preserver_original_keys: creating a Hash from the wrapper preserves symbols and strings as keys. Default: true.



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?

Returns:

  • (Boolean)


37
38
39
# File 'lib/libis/tools/deep_struct.rb', line 37

def key?(key)
  self.respond_to?(key)
end

#keysObject



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