Class: EightBall::Parsers::Json

Inherits:
Object
  • Object
show all
Defined in:
lib/eight_ball/parsers/json.rb

Overview

A JSON parser will parse JSON into a list of Features. The top-level JSON element must be an array and must use camel-case; this will be converted to snake-case by EightBall.

Below are some examples of valid JSON:

Examples:

A single Feature is enabled for accounts 1-5 as well as region Europe

[{
  "name": "Feature1",
  "enabledFor": [{
    "type": "range",
    "parameter": "accountId",
    "min": 1,
    "max": 5
  }, {
    "type": "list",
    "parameter": "regionName",
    "values": ["Europe"]
  }]
}]

A single Feature is disabled completely using the Always condition

[{
  "name": "Feature1",
  "disabledFor": [{
    "type": "always"
  }]
}]

Instance Method Summary collapse

Instance Method Details

#parse(json) ⇒ Array<EightBall::Feature>

Convert the JSON into a list of Features.

Examples:

json_string = <Read from somewhere>

parser = EightBall::Parsers::Json.new
parser.parse json_string => [Features]

Parameters:

  • json (String)

    The JSON string to parse.

Returns:



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/eight_ball/parsers/json.rb', line 45

def parse(json)
  parsed = JSON.parse(json, :symbolize_names => true).to_snake_keys
  
  raise ArgumentError, 'JSON input was not an array' unless parsed.is_a? Array

  parsed.map do |feature|
    enabled_for = create_conditions feature[:enabled_for]
    disabled_for = create_conditions feature[:disabled_for]

    EightBall::Feature.new feature[:name], enabled_for, disabled_for
  end
rescue JSON::ParserError => e
  EightBall.logger.error { "Failed to parse JSON: #{e.message}" }
  []
end