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? to_hash].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, *_args) ⇒ Object

Raises:

  • (ArgumentError)


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

def method_missing(method, *_args)
  return if @allow_nil
  raise ArgumentError.new("There is no option :#{method} in configuration.")
end

Instance Method Details

#[](key) ⇒ Object



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

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

#respond_to_missing?(*_args) ⇒ Boolean

Returns:

  • (Boolean)


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

def respond_to_missing?(*_args)
  true
end

#to_hashObject



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/config_default/struct.rb', line 30

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