require 'json' module LaunchDarkly # # A snapshot of the state of all feature flags with regard to a specific context, generated by # calling the {LDClient#all_flags_state}. Serializing this object to JSON using # `JSON.generate` (or the `to_json` method) will produce the appropriate data structure for # bootstrapping the LaunchDarkly JavaScript client. # class FeatureFlagsState def initialize(valid) @flag_values = {} @flag_metadata = {} @valid = valid end # Used internally to build the state map. # @private def add_flag(flag_state, with_reasons, details_only_if_tracked) key = flag_state[:key] @flag_values[key] = flag_state[:value] meta = {} omit_details = false if details_only_if_tracked if !flag_state[:trackEvents] && !flag_state[:trackReason] && !(flag_state[:debugEventsUntilDate] && flag_state[:debugEventsUntilDate] > Impl::Util::current_time_millis) omit_details = true end end reason = (!with_reasons and !flag_state[:trackReason]) ? nil : flag_state[:reason] if !reason.nil? && !omit_details meta[:reason] = reason end unless omit_details meta[:version] = flag_state[:version] end meta[:variation] = flag_state[:variation] unless flag_state[:variation].nil? meta[:trackEvents] = true if flag_state[:trackEvents] meta[:trackReason] = true if flag_state[:trackReason] meta[:debugEventsUntilDate] = flag_state[:debugEventsUntilDate] if flag_state[:debugEventsUntilDate] @flag_metadata[key] = meta end # Returns true if this object contains a valid snapshot of feature flag state, or false if the # state could not be computed (for instance, because the client was offline or there was no context). def valid? @valid end # Returns the value of an individual feature flag at the time the state was recorded. # Returns nil if the flag returned the default value, or if there was no such flag. def flag_value(key) @flag_values[key] end # Returns a map of flag keys to flag values. If a flag would have evaluated to the default value, # its value will be nil. # # Do not use this method if you are passing data to the front end to "bootstrap" the JavaScript client. # Instead, use as_json. def values_map @flag_values end # Returns a hash that can be used as a JSON representation of the entire state map, in the format # used by the LaunchDarkly JavaScript SDK. Use this method if you are passing data to the front end # in order to "bootstrap" the JavaScript client. # # Do not rely on the exact shape of this data, as it may change in future to support the needs of # the JavaScript client. def as_json(*) # parameter is unused, but may be passed if we're using the json gem ret = @flag_values.clone ret['$flagsState'] = @flag_metadata ret['$valid'] = @valid ret end # Same as as_json, but converts the JSON structure into a string. def to_json(*a) as_json.to_json(a) end end end