class EightBall::Marshallers::Json

Public Instance Methods

marshall(features) click to toggle source

Convert the given {EightBall::Feature Features} into a JSON array.

@param [Array<EightBall::Feature>] features The {EightBall::Feature Features} to convert. @return [String] The resulting JSON string.

@example

json_string = <Read from somewhere>

marshaller = EightBall::Marshallers::Json.new
marshaller.marshall [Array<EightBall::Feature>] => json
# File lib/eight_ball/marshallers/json.rb, line 50
def marshall(features)
  JSON.generate(features.map { |feature| feature_to_hash(feature).to_camelback_keys })
end
unmarshall(json) click to toggle source

Convert the given JSON into a list of {EightBall::Feature Features}.

@param [String] json The JSON string to convert. @return [Array<EightBall::Feature>] The parsed {EightBall::Feature Features}

@example

json_string = <Read from somewhere>

marshaller = EightBall::Marshallers::Json.new
marshaller.unmarshall json_string => [Features]
# File lib/eight_ball/marshallers/json.rb, line 64
def unmarshall(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_from_json feature[:enabled_for]
    disabled_for = create_conditions_from_json 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

Private Instance Methods

condition_to_hash(condition) click to toggle source
# File lib/eight_ball/marshallers/json.rb, line 93
def condition_to_hash(condition)
  hash = {
    type: condition.class.name.split('::').last.downcase
  }
  condition.instance_variables.each do |var|
    next unless condition.instance_variable_get(var)

    hash[var.to_s.delete('@')] = condition.instance_variable_get(var)
  end

  hash
end
create_conditions_from_json(json_conditions) click to toggle source
# File lib/eight_ball/marshallers/json.rb, line 106
def create_conditions_from_json(json_conditions)
  return [] unless json_conditions&.is_a?(Array)

  json_conditions.map do |condition|
    condition_class = EightBall::Conditions.by_name condition[:type]
    condition_class.new condition
  end
end
feature_to_hash(feature) click to toggle source
# File lib/eight_ball/marshallers/json.rb, line 82
def feature_to_hash(feature)
  hash = {
    name: feature.name
  }

  hash[:enabled_for] = feature.enabled_for.map { |condition| condition_to_hash(condition) } unless feature.enabled_for.empty?
  hash[:disabled_for] = feature.disabled_for.map { |condition| condition_to_hash(condition) } unless feature.disabled_for.empty?

  hash
end