Class: ConfigDefault::Struct

Inherits:
Object
  • Object
show all
Defined in:
lib/config_default/struct.rb

Constant Summary collapse

RESERVED_METHODS =
%i[method_missing respond_to_missing? inspect to_hash to_s].freeze

Instance Method Summary collapse

Constructor Details

#initialize(attributes, recursive: false, allow_nil: false) ⇒ Struct

Returns a new instance of Struct.



6
7
8
9
10
11
12
13
14
15
# File 'lib/config_default/struct.rb', line 6

def initialize(attributes, recursive: false, allow_nil: false)
  @attributes = ActiveSupport::HashWithIndifferentAccess.new(attributes)
  @allow_nil = allow_nil
  @recursive = recursive

  make_recursive!
  define_methods!

  @attributes.freeze
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



21
22
23
24
# File 'lib/config_default/struct.rb', line 21

def method_missing(method_name, *args, &block)
  return if @allow_nil
  super
end

Instance Method Details

#[](key) ⇒ Object



17
18
19
# File 'lib/config_default/struct.rb', line 17

def [](key)
  @attributes[key]
end

#inspectObject



30
31
32
33
# File 'lib/config_default/struct.rb', line 30

def inspect
  "#<ConfigDefault::Struct @attributes=#{to_hash} " \
    "@recursive=#{@recursive} @allow_nil=#{@allow_nil}>"
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/config_default/struct.rb', line 26

def respond_to_missing?(method_name, include_private = false)
  @attributes.key?(method_name) || super
end

#to_hashObject



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/config_default/struct.rb', line 35

def to_hash
  dup = @attributes.dup

  if @recursive
    dup.each do |key, value|
      next unless value.is_a?(self.class)
      dup[key] = value.to_hash
    end
  end

  dup
end