Class: JsonRspecMatchMaker::TargetValue

Inherits:
Object
  • Object
show all
Defined in:
lib/json_rspec_match_maker/target_value.rb

Overview

Handles fetching the target value from the target object

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, each_opts, target) ⇒ TargetValue

Returns a new instance of TargetValue.



6
7
8
9
# File 'lib/json_rspec_match_maker/target_value.rb', line 6

def initialize(key, each_opts, target)
  @error_key = full_error_key(key, each_opts)
  @value = fetch_value(key, each_opts, target)
end

Instance Attribute Details

#error_keyObject (readonly)

Returns the value of attribute error_key.



4
5
6
# File 'lib/json_rspec_match_maker/target_value.rb', line 4

def error_key
  @error_key
end

#valueObject (readonly)

Returns the value of attribute value.



4
5
6
# File 'lib/json_rspec_match_maker/target_value.rb', line 4

def value
  @value
end

Instance Method Details

#==(other) ⇒ Object

Raises:

  • (ArgumentError)


30
31
32
33
# File 'lib/json_rspec_match_maker/target_value.rb', line 30

def ==(other)
  raise ArgumentError unless other.is_a? ExpectedValue
  other.value == value
end

#fetch_value(key, each_opts, target) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/json_rspec_match_maker/target_value.rb', line 17

def fetch_value(key, each_opts, target)
  return value_for_key(key, target) if each_opts.nil?

  targets = value_for_key(key, target)
  specific_target = targets[each_opts[:idx]]
  value_for_key(each_opts[:error_key], specific_target)
end

#full_error_key(key, each_opts) ⇒ Object



11
12
13
14
15
# File 'lib/json_rspec_match_maker/target_value.rb', line 11

def full_error_key(key, each_opts)
  return key if each_opts.nil?

  "#{key}[#{each_opts[:idx]}].#{each_opts[:error_key]}"
end

#value_for_key(key, json) ⇒ Object



25
26
27
28
# File 'lib/json_rspec_match_maker/target_value.rb', line 25

def value_for_key(key, json)
  value = key.split('.').reduce(json) { |j, k| j.fetch(k, {}) }
  value == {} ? nil : value
end