Class: Grape::Util::BaseInheritable

Inherits:
Object
  • Object
show all
Defined in:
lib/grape/util/base_inheritable.rb

Overview

Base for classes which need to operate with own values kept in the hash and inherited values kept in a Hash-like object.

@new_values is lazily allocated on first write so settings layers that only inherit (never override) don’t carry an empty Hash each.

Direct Known Subclasses

InheritableValues, StackableValues

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(inherited_values = nil) ⇒ BaseInheritable

Returns a new instance of BaseInheritable.

Parameters:

  • inherited_values (Object) (defaults to: nil)

    An object implementing an interface of the Hash class.



15
16
17
18
# File 'lib/grape/util/base_inheritable.rb', line 15

def initialize(inherited_values = nil)
  @inherited_values = inherited_values || {}
  # @new_values stays nil until the first write.
end

Instance Attribute Details

#inherited_valuesObject

Returns the value of attribute inherited_values.



11
12
13
# File 'lib/grape/util/base_inheritable.rb', line 11

def inherited_values
  @inherited_values
end

#new_valuesObject

Returns the value of attribute new_values.



11
12
13
# File 'lib/grape/util/base_inheritable.rb', line 11

def new_values
  @new_values
end

Instance Method Details

#delete(*keys) ⇒ Object



20
21
22
23
24
# File 'lib/grape/util/base_inheritable.rb', line 20

def delete(*keys)
  return [] unless @new_values

  keys.map { |key| @new_values.delete(key) }
end

#initialize_copy(other) ⇒ Object



26
27
28
29
30
# File 'lib/grape/util/base_inheritable.rb', line 26

def initialize_copy(other)
  super
  @inherited_values = other.inherited_values
  @new_values = other.new_values&.dup
end

#key?(name) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/grape/util/base_inheritable.rb', line 38

def key?(name)
  @inherited_values.key?(name) || @new_values&.key?(name) || false
end

#keysObject



32
33
34
35
36
# File 'lib/grape/util/base_inheritable.rb', line 32

def keys
  return @inherited_values.keys if @new_values.nil? || @new_values.empty?

  (@inherited_values.keys + @new_values.keys).uniq
end