module JsonTest::Helpers

Public Instance Methods

generate_normalized_json(ruby) click to toggle source
# File lib/jsontest/helpers.rb, line 19
def generate_normalized_json(ruby)
  case ruby
  when Hash, Array then JSON.pretty_generate(ruby)
  else ruby.to_json
  end
end
load_json(relative_path) click to toggle source
# File lib/jsontest/helpers.rb, line 26
def load_json(relative_path)
  missing_json_directory! if JsonTest.directory.nil?
  path = File.join(JsonTest.directory, relative_path)
  missing_json_file!(path) unless File.exist?(path)
  File.read(path)
end
normalize_json(json, path = nil) click to toggle source
# File lib/jsontest/helpers.rb, line 14
def normalize_json(json, path = nil)
  ruby = parse_json(json, path)
  generate_normalized_json(ruby)
end
parse_json(json, path = nil) click to toggle source
# File lib/jsontest/helpers.rb, line 7
def parse_json(json, path = nil)
  ruby = MultiJson.decode("[#{json}]").first
  value_at_json_path(ruby, path)
rescue MultiJson::DecodeError
  MultiJson.decode(json)
end

Private Instance Methods

missing_json_directory!() click to toggle source
# File lib/jsontest/helpers.rb, line 54
def missing_json_directory!
  raise JsonTest::MissingDirectory
end
missing_json_file!(path) click to toggle source
# File lib/jsontest/helpers.rb, line 58
def missing_json_file!(path)
  raise JsonTest::MissingFile.new(path)
end
missing_json_path!(path) click to toggle source
# File lib/jsontest/helpers.rb, line 50
def missing_json_path!(path)
  raise JsonTest::MissingPath.new(path)
end
value_at_json_path(ruby, path) click to toggle source
# File lib/jsontest/helpers.rb, line 34
def value_at_json_path(ruby, path)
  return ruby unless path

  path.split("/").inject(ruby) do |value, key|
    case value
    when Hash
      value.fetch(key){ missing_json_path!(path) }
    when Array
      missing_json_path!(path) unless key =~ /^\d+$/
      value.fetch(key.to_i){ missing_json_path!(path) }
    else
      missing_json_path!(path)
    end
  end
end