Class: Karafka::Web::Ui::Lib::HashProxy

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/karafka/web/ui/lib/hash_proxy.rb

Overview

Proxy for hashes we use across UI. Often we have nested values we want to extract or just values we want to reference and this object drastically simplifies that.

It is mostly used for flat hashes.

It is in a way similar to openstruct but has abilities to dive deep into objects

It is not super fast but it is enough for the UI and how deep structures we have.

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ HashProxy

Returns a new instance of HashProxy.

Parameters:

  • hash (Hash)

    hash we want to convert to a proxy



23
24
25
26
27
28
29
30
31
# File 'lib/karafka/web/ui/lib/hash_proxy.rb', line 23

def initialize(hash)
  @hash = hash
  # Nodes we already visited in the context of a given attribute lookup
  # We cache them not to look for them over and over again if they are used more than
  # once
  @visited = Hash.new { |h, k| h[k] = {} }
  # Methods invocations cache
  @results = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

Parameters:

  • method_name (String)

    method name

  • args (Object)

    all the args of the method

  • block (Proc)

    block for the method



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/karafka/web/ui/lib/hash_proxy.rb', line 41

def method_missing(method_name, *args, &block)
  method_name = method_name.to_sym

  return super unless args.empty? && block.nil?
  return @results[method_name] if @results.key?(method_name)

  result = deep_find(@hash, method_name)

  return super if result.nil?

  @results[method_name] = result
end

Instance Method Details

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

Parameters:

  • method_name (String)

    method name

  • include_private (Boolean) (defaults to: false)

Returns:

  • (Boolean)


56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/karafka/web/ui/lib/hash_proxy.rb', line 56

def respond_to_missing?(method_name, include_private = false)
  method_name = method_name.to_sym

  return true if @results.key?(method_name)

  result = deep_find(@hash, method_name)

  return super if result.nil?

  @results[method_name] = result

  true
end

#to_hOriginal hash

Returns:

  • (Original hash)


34
35
36
# File 'lib/karafka/web/ui/lib/hash_proxy.rb', line 34

def to_h
  @hash
end