Class: Jerakia::Answer

Inherits:
Object
  • Object
show all
Defined in:
lib/jerakia/answer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lookup_type = :first, merge_strategy = :array) ⇒ Answer

Returns a new instance of Answer


10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/jerakia/answer.rb', line 10

def initialize(lookup_type = :first, merge_strategy = :array)
  @lookup_type = lookup_type
  @merge_strategy = merge_strategy
  @found = false
  case lookup_type
  when :first
    @payload = nil
  when :cascade
    @payload = []
    @datatype = 'array'
  end
end

Instance Attribute Details

#datatypeObject

Returns the value of attribute datatype


6
7
8
# File 'lib/jerakia/answer.rb', line 6

def datatype
  @datatype
end

#lookup_typeObject (readonly)

Returns the value of attribute lookup_type


8
9
10
# File 'lib/jerakia/answer.rb', line 8

def lookup_type
  @lookup_type
end

#merge_strategyObject (readonly)

Returns the value of attribute merge_strategy


7
8
9
# File 'lib/jerakia/answer.rb', line 7

def merge_strategy
  @merge_strategy
end

#payloadObject

Returns the value of attribute payload


5
6
7
# File 'lib/jerakia/answer.rb', line 5

def payload
  @payload
end

Instance Method Details

#consolidateObject


47
48
49
50
51
52
53
54
55
56
# File 'lib/jerakia/answer.rb', line 47

def consolidate
  if lookup_type == :cascade && payload.is_a?(Array)
    case merge_strategy
    when :array
      flatten_payload!
    when :hash, :deep_hash
      merge_payload!
    end
  end
end

#flatten_payload!Object


59
60
61
# File 'lib/jerakia/answer.rb', line 59

def flatten_payload!
  @payload.flatten!
end

#found?Boolean

Returns:

  • (Boolean)

43
44
45
# File 'lib/jerakia/answer.rb', line 43

def found?
  @found
end

#merge_payload!Object

TODO: consolidate this into less lines


65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/jerakia/answer.rb', line 65

def merge_payload! # rubocop:disable Metrics/MethodLength
  payload_hash = {}
  @payload.each do |p|
    next unless p.is_a?(Hash)
    case merge_strategy
    when :hash
      payload_hash = p.merge(payload_hash)
    when :deep_hash
      payload_hash = p.deep_merge!(payload_hash)
    end
  end
  @payload = payload_hash
  set_data_type
end

#process_response(response_entries) ⇒ Object


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/jerakia/answer.rb', line 23

def process_response(response_entries)
  responses = response_entries.flatten.compact

  return nil if responses.empty?
  @found = true

  responses.each do |res|
    case lookup_type
    when :first
      @payload = res.value
      @datatype = res.datatype
      Jerakia.log.debug("Registered answer as #{payload}")
      break
    when :cascade
      @payload << res.value
    end
  end
  consolidate
end

#set_data_typeObject


80
81
82
# File 'lib/jerakia/answer.rb', line 80

def set_data_type
  @data_type = @payload.class.to_s.downcase
end