Module: Airborne::PathMatcher

Defined in:
lib/spaceborne.rb

Overview

extension to handle hash value checking

Instance Method Summary collapse

Instance Method Details

#ensure_array_or_hash(path, json) ⇒ Object

Raises:

  • (RSpec::Expectations::ExpectationNotMetError)


210
211
212
213
214
215
# File 'lib/spaceborne.rb', line 210

def ensure_array_or_hash(path, json)
  return if json.class == Array || json.class == Hash
  raise RSpec::Expectations::ExpectationNotMetError,
        "Expected #{path} to be array or hash, got #{json.class}"\
        ' from JSON response'
end

#get_by_path(path, json, &block) ⇒ Object

Raises:

  • (PathError)


174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/spaceborne.rb', line 174

def get_by_path(path, json, &block)
  raise PathError, "Invalid Path, contains '..'" if /\.\./ =~ path
  type = false
  parts = path.to_s.split('.')
  parts.each_with_index do |part, index|
    if %w[* ?].include?(part)
      ensure_array_or_hash(path, json)
      type = part
      if index < parts.length.pred
        walk_with_path(type, index, path, parts, json, &block) && return
      end
      next
    end
    begin
      json = process_json(part, json)
    rescue StandardError
      raise PathError,
            "Expected #{json.class}\nto be an object with property #{part}"
    end
  end
  if type == '*'
    case json.class.name
    when 'Array'
      expect_all(json, &block)
    when 'Hash'
      json.each do |k, _v|
        yield json[k]
      end
    end
  elsif type == '?'
    expect_one(path, json, &block)
  else
    yield json
  end
end