zenmanage 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +27 -0
  3. data/CODE_OF_CONDUCT.md +84 -0
  4. data/CONTRIBUTING.md +22 -0
  5. data/LICENSE +21 -0
  6. data/README.md +382 -0
  7. data/SECURITY.md +9 -0
  8. data/examples/caching.rb +58 -0
  9. data/examples/context_based_flags.rb +45 -0
  10. data/examples/defaults.rb +62 -0
  11. data/examples/percentage_rollouts.rb +37 -0
  12. data/examples/rails_integration.rb +74 -0
  13. data/examples/simple_flags.rb +41 -0
  14. data/lib/generators/zenmanage/install/install_generator.rb +18 -0
  15. data/lib/generators/zenmanage/install/templates/initializer.rb +23 -0
  16. data/lib/zenmanage/api_client.rb +264 -0
  17. data/lib/zenmanage/attribute.rb +55 -0
  18. data/lib/zenmanage/cache/base.rb +46 -0
  19. data/lib/zenmanage/cache/filesystem_cache.rb +88 -0
  20. data/lib/zenmanage/cache/memory_cache.rb +63 -0
  21. data/lib/zenmanage/cache/null_cache.rb +22 -0
  22. data/lib/zenmanage/config_builder.rb +215 -0
  23. data/lib/zenmanage/configuration.rb +118 -0
  24. data/lib/zenmanage/context.rb +125 -0
  25. data/lib/zenmanage/defaults_collection.rb +68 -0
  26. data/lib/zenmanage/errors.rb +21 -0
  27. data/lib/zenmanage/flag.rb +200 -0
  28. data/lib/zenmanage/flag_manager.rb +197 -0
  29. data/lib/zenmanage/hash_access.rb +72 -0
  30. data/lib/zenmanage/rails/controller_helpers.rb +85 -0
  31. data/lib/zenmanage/rails/middleware.rb +34 -0
  32. data/lib/zenmanage/rails/railtie.rb +60 -0
  33. data/lib/zenmanage/rollout.rb +45 -0
  34. data/lib/zenmanage/rollout_bucket.rb +40 -0
  35. data/lib/zenmanage/rule.rb +142 -0
  36. data/lib/zenmanage/rule_engine.rb +156 -0
  37. data/lib/zenmanage/rule_store.rb +164 -0
  38. data/lib/zenmanage/target.rb +37 -0
  39. data/lib/zenmanage/version.rb +6 -0
  40. data/lib/zenmanage/webhook.rb +89 -0
  41. data/lib/zenmanage.rb +183 -0
  42. metadata +216 -0
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ # Base error class for all Zenmanage SDK exceptions.
5
+ class Error < StandardError; end
6
+
7
+ # Raised when configuration is invalid or missing required values.
8
+ class ConfigurationError < Error; end
9
+
10
+ # Raised when fetching rules from the API fails after all retries.
11
+ class FetchRulesError < Error; end
12
+
13
+ # Raised when rules JSON is malformed or invalid.
14
+ class InvalidRulesError < Error; end
15
+
16
+ # Raised when a flag is not found and no default is provided.
17
+ class EvaluationError < Error; end
18
+
19
+ # Raised when a cache operation fails.
20
+ class CacheError < Error; end
21
+ end
@@ -0,0 +1,200 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ # Represents a feature flag with its metadata, rules, and evaluated target value.
5
+ #
6
+ # Instances are returned by {FlagManager#single} and {FlagManager#all}.
7
+ #
8
+ # @example Boolean flag
9
+ # flag = client.flags.single("dark-mode")
10
+ # if flag.enabled?
11
+ # # render dark mode
12
+ # end
13
+ #
14
+ # @example String flag
15
+ # variant = client.flags.single("checkout-layout").as_string
16
+ #
17
+ # @example Number flag
18
+ # limit = client.flags.single("rate-limit").as_number
19
+ #
20
+ # @example JSON flag
21
+ # config = client.flags.single("checkout-config").as_json
22
+ class Flag
23
+ # Flag types this release of the SDK knows how to evaluate. Any other
24
+ # value (e.g. served by a newer API to an older SDK) is treated as
25
+ # unparseable so the flag is dropped by {FlagManager#parse_flags} and
26
+ # lookups fall back to the caller's default, the same as a missing flag.
27
+ KNOWN_TYPES = %w[boolean string number json].freeze
28
+
29
+ attr_reader :version, :type, :key, :name, :target, :rules, :rollout
30
+
31
+ # @param version [String]
32
+ # @param type [String] `"boolean"`, `"string"`, `"number"`, or `"json"`
33
+ # @param key [String] unique flag identifier
34
+ # @param name [String] human-readable flag name
35
+ # @param target [Target] the evaluated target value
36
+ # @param rules [Array<Rule>]
37
+ # @param rollout [Rollout, nil]
38
+ def initialize(version:, type:, key:, name:, target:, rules: [], rollout: nil)
39
+ @version = version.to_s
40
+ @type = type.to_s
41
+ @key = key.to_s
42
+ @name = name.to_s
43
+ @target = target
44
+ @rules = Array(rules)
45
+ @rollout = rollout
46
+ end
47
+
48
+ # Whether a boolean flag is on. Always `false` for string, number and json flags.
49
+ #
50
+ # @return [Boolean]
51
+ def enabled?
52
+ @type == "boolean" && as_bool
53
+ end
54
+
55
+ # The flag value as a boolean.
56
+ #
57
+ # A boolean flag returns its value. Every other type returns `true`, whatever its
58
+ # value is (the cross-SDK coercion contract); use {#enabled?} to ask whether a
59
+ # boolean flag is on.
60
+ #
61
+ # @return [Boolean]
62
+ def as_bool
63
+ raw = @target.value.value
64
+ return truthy?(raw) unless raw.is_a?(Hash)
65
+ return !!raw["boolean"] if raw.key?("boolean")
66
+ return true if wrapped?(raw)
67
+
68
+ truthy?(raw.values.first)
69
+ end
70
+
71
+ # The value of a string flag. Empty for boolean, number and json flags.
72
+ #
73
+ # @return [String]
74
+ def as_string
75
+ raw = @target.value.value
76
+ return raw.to_s unless raw.is_a?(Hash)
77
+ return raw["string"].to_s if raw.key?("string")
78
+ return "" if wrapped?(raw)
79
+
80
+ raw.values.first.to_s
81
+ end
82
+
83
+ # The value of a number flag. `0` for boolean, string and json flags.
84
+ #
85
+ # @return [Numeric]
86
+ def as_number
87
+ raw = @target.value.value
88
+ return to_number(raw) unless raw.is_a?(Hash)
89
+ return to_number(raw["number"]) if raw.key?("number")
90
+ return 0 if wrapped?(raw)
91
+
92
+ to_number(raw.values.first)
93
+ end
94
+
95
+ # The decoded value of a json flag: a Hash for a JSON object, an Array for a JSON
96
+ # array. An empty Hash for boolean, string and number flags, and for a json value
97
+ # that is a bare scalar.
98
+ #
99
+ # Rails' JSON encoder also calls `as_json`, so `render json: flag` renders this
100
+ # value. To send a whole flag, render {#to_h}. Serializers that pass an options
101
+ # argument get {#to_h}.
102
+ #
103
+ # @return [Hash, Array]
104
+ def as_json(*serializer_options)
105
+ return to_h unless serializer_options.empty?
106
+
107
+ raw = @target.value.value
108
+ return {} unless raw.is_a?(Hash)
109
+
110
+ val = raw["json"]
111
+ return val if val.is_a?(Hash) || val.is_a?(Array)
112
+
113
+ {}
114
+ end
115
+
116
+ # Return the raw flag value.
117
+ #
118
+ # @return [Object]
119
+ def value
120
+ raw = @target.value.value
121
+ return raw unless raw.is_a?(Hash)
122
+
123
+ # Return the most appropriate typed value
124
+ return raw["boolean"] unless raw["boolean"].nil?
125
+ return raw["string"] unless raw["string"].nil?
126
+ return raw["number"] unless raw["number"].nil?
127
+ return raw["json"] unless raw["json"].nil?
128
+
129
+ raw.values.first
130
+ end
131
+
132
+ # @return [String]
133
+ def to_s
134
+ @key
135
+ end
136
+
137
+ # @param data [Hash]
138
+ # @return [Flag]
139
+ # @raise [ArgumentError] if `type` is not one of {KNOWN_TYPES} — e.g. a
140
+ # flag type served by a newer API than this SDK release supports.
141
+ def self.from_hash(data)
142
+ rollout_data = HashAccess.value(data, :rollout)
143
+ type = HashAccess.string(data, :type, "boolean")
144
+
145
+ unless KNOWN_TYPES.include?(type)
146
+ raise ArgumentError, "Unsupported flag type #{type.inspect} for flag #{HashAccess.string(data, :key, "")}"
147
+ end
148
+
149
+ new(
150
+ version: HashAccess.string(data, :version, ""),
151
+ type: type,
152
+ key: HashAccess.string(data, :key, ""),
153
+ name: HashAccess.string(data, :name, ""),
154
+ target: Target.from_hash(HashAccess.hash(data, :target)),
155
+ rules: HashAccess.array(data, :rules).map { |r| Rule.from_hash(r) },
156
+ rollout: rollout_data.is_a?(Hash) ? Rollout.from_hash(rollout_data) : nil,
157
+ )
158
+ end
159
+
160
+ # @return [Hash]
161
+ def to_h
162
+ h = {
163
+ "version" => @version,
164
+ "type" => @type,
165
+ "key" => @key,
166
+ "name" => @name,
167
+ "target" => @target.to_h,
168
+ "rules" => @rules.map(&:to_h),
169
+ }
170
+ h["rollout"] = @rollout.to_h if @rollout
171
+ h
172
+ end
173
+
174
+ private
175
+
176
+ # Whether a value Hash is one of the wrappers this release knows.
177
+ #
178
+ # @return [Boolean]
179
+ def wrapped?(raw)
180
+ KNOWN_TYPES.any? { |type| raw.key?(type) }
181
+ end
182
+
183
+ # Truthiness for a value with no recognised wrapper: empty strings and zero are
184
+ # false, anything else follows plain Ruby truthiness.
185
+ #
186
+ # @return [Boolean]
187
+ def truthy?(val)
188
+ case val
189
+ when String then !val.empty?
190
+ when Numeric then !val.zero?
191
+ else !!val
192
+ end
193
+ end
194
+
195
+ # @return [Numeric]
196
+ def to_number(val)
197
+ val.is_a?(Numeric) ? val : val.to_s.to_f
198
+ end
199
+ end
200
+ end
@@ -0,0 +1,197 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ # Orchestrates fetching, caching, and evaluating feature flags.
5
+ #
6
+ # Instances are obtained via {Zenmanage::Client#flags}. The FlagManager is
7
+ # immutable with respect to context and defaults — `with_context` and
8
+ # `with_defaults` return new instances that share the loaded rules, so rules are
9
+ # fetched once per client and a refresh is seen by every manager.
10
+ #
11
+ # @example
12
+ # flags = client.flags
13
+ # .with_context(Zenmanage::Context.single("user", current_user.id))
14
+ #
15
+ # flags.single("dark-mode").enabled?
16
+ class FlagManager
17
+ CACHE_KEY = RuleStore::CACHE_KEY
18
+
19
+ # @param api_client [ApiClient]
20
+ # @param cache [Cache::Base]
21
+ # @param rule_engine [RuleEngine]
22
+ # @param cache_ttl [Integer] seconds before the rules are reloaded
23
+ # @param logger [#debug, #info, #warn, #error]
24
+ # @param cache_key [String] where this manager's rules live in the cache
25
+ def initialize(api_client:, cache:, rule_engine:, cache_ttl:, logger: NullLogger.new, cache_key: CACHE_KEY)
26
+ @api_client = api_client
27
+ @rule_engine = rule_engine
28
+ @store = RuleStore.new(
29
+ api_client: api_client, cache: cache, cache_ttl: cache_ttl, logger: logger, cache_key: cache_key,
30
+ )
31
+ @context = Context.new("anonymous")
32
+ @defaults = DefaultsCollection.new
33
+ end
34
+
35
+ # Return all flags evaluated against the current context. Keys that only exist in
36
+ # the {DefaultsCollection} are included with their default value, so a total
37
+ # rule-loading failure returns the configured defaults.
38
+ #
39
+ # Does not report usage.
40
+ #
41
+ # @return [Array<Flag>]
42
+ def all
43
+ loaded = @store.flags
44
+ fallbacks = @defaults.all.reject { |key, value| loaded.key?(key) || value.nil? }
45
+
46
+ loaded.values.map { |flag| evaluate_flag(flag) } +
47
+ fallbacks.map { |key, value| create_flag_from_default(key, value) }
48
+ end
49
+
50
+ # Return a single flag by key, evaluated against the current context, and report
51
+ # its usage.
52
+ #
53
+ # Priority order when the flag is not found (including when rule-loading
54
+ # failed outright, e.g. an unreachable environment):
55
+ # 1. `default` argument
56
+ # 2. Value from {DefaultsCollection}
57
+ # 3. Raises {EvaluationError}
58
+ #
59
+ # @param key [String]
60
+ # @param default [Boolean, String, Numeric, Hash, Array, nil] inline fallback value
61
+ # @return [Flag]
62
+ # @raise [EvaluationError] if the flag is not found and no default is set
63
+ def single(key, default = nil)
64
+ key = key.to_s
65
+ flag = @store.flags[key]
66
+ # The default the caller would have fallen back to is recorded on every usage
67
+ # report, not only on the fallback paths.
68
+ fallback = default.nil? ? @defaults.get(key) : default
69
+
70
+ raise EvaluationError, not_found_message(key) if flag.nil? && fallback.nil?
71
+
72
+ report_usage(key, usage_context, fallback)
73
+ flag ? evaluate_flag(flag) : create_flag_from_default(key, fallback)
74
+ end
75
+
76
+ # Return a new FlagManager with the given context applied.
77
+ #
78
+ # @param context [Context]
79
+ # @return [FlagManager]
80
+ def with_context(context)
81
+ dup.tap { |copy| copy.context = context }
82
+ end
83
+
84
+ # Return a new FlagManager with the given defaults applied.
85
+ #
86
+ # @param defaults [DefaultsCollection]
87
+ # @return [FlagManager]
88
+ def with_defaults(defaults)
89
+ dup.tap { |copy| copy.defaults = defaults }
90
+ end
91
+
92
+ # Fetch the rules from the API now, bypassing the cache.
93
+ #
94
+ # @return [void]
95
+ # @raise [FetchRulesError, InvalidRulesError] if they can't be fetched; the rules
96
+ # already loaded are kept
97
+ def refresh_rules
98
+ @store.refresh!
99
+ end
100
+
101
+ # Report that a flag was used. {#single} does this for you.
102
+ #
103
+ # @param key [String]
104
+ # @param context [Context, nil]
105
+ # @param default_value [Boolean, String, Numeric, Hash, Array, nil]
106
+ # @return [Thread, nil] the background thread sending the report
107
+ def report_usage(key, context = nil, default_value = nil)
108
+ @api_client.report_usage(key, context, default_value)
109
+ end
110
+
111
+ protected
112
+
113
+ attr_writer :context, :defaults
114
+
115
+ private
116
+
117
+ def not_found_message(key)
118
+ error = @store.last_error
119
+ error ? "Flag not found: #{key} (rules failed to load: #{error.message})" : "Flag not found: #{key}"
120
+ end
121
+
122
+ def evaluate_flag(flag)
123
+ target, rules = rollout_selection(flag)
124
+
125
+ # Evaluate rules against a temporary flag carrying the selected target/rules
126
+ matched_value = @rule_engine.evaluate(flag_with(flag, target, rules), @context)
127
+ return flag_with(flag, target_valued(target, matched_value), rules) if matched_value
128
+
129
+ # Return flag with selected target (rollout or original)
130
+ return flag if target.equal?(flag.target)
131
+
132
+ flag_with(flag, target, rules)
133
+ end
134
+
135
+ # The target/rules pair to evaluate: the rollout's when the context falls
136
+ # inside the rollout bucket, otherwise the flag's own.
137
+ #
138
+ # @return [Array(Target, Array<Rule>)]
139
+ def rollout_selection(flag)
140
+ rollout = flag.rollout
141
+ in_bucket = rollout && RolloutBucket.in_bucket?(rollout.salt, @context.identifier, rollout.percentage)
142
+
143
+ in_bucket ? [rollout.target, rollout.rules] : [flag.target, flag.rules]
144
+ end
145
+
146
+ # Copy +flag+'s identity onto a different target/rules pair.
147
+ #
148
+ # @return [Flag]
149
+ def flag_with(flag, target, rules)
150
+ Flag.new(
151
+ version: flag.version,
152
+ type: flag.type,
153
+ key: flag.key,
154
+ name: flag.name,
155
+ target: target,
156
+ rules: rules,
157
+ )
158
+ end
159
+
160
+ # Copy +target+ with the value a matching rule produced.
161
+ #
162
+ # @return [Target]
163
+ def target_valued(target, value)
164
+ Target.new(
165
+ version: target.version,
166
+ expired_at: target.expired_at,
167
+ published_at: target.published_at,
168
+ scheduled_at: target.scheduled_at,
169
+ value: RuleValue.new(target.value.version, value),
170
+ )
171
+ end
172
+
173
+ def create_flag_from_default(key, default_value)
174
+ type, wrapped = case default_value
175
+ when TrueClass, FalseClass then ["boolean", { "boolean" => default_value }]
176
+ when Integer, Float then ["number", { "number" => default_value }]
177
+ when Hash, Array then ["json", { "json" => default_value }]
178
+ else ["string", { "string" => default_value.to_s }]
179
+ end
180
+
181
+ target = Target.new(
182
+ value: RuleValue.new("default", wrapped),
183
+ )
184
+
185
+ Flag.new(version: "default", type: type, key: key, name: key, target: target)
186
+ end
187
+
188
+ def usage_context
189
+ return nil if @context.type == "anonymous" &&
190
+ @context.name.nil? &&
191
+ @context.identifier.nil? &&
192
+ @context.attributes.empty?
193
+
194
+ @context
195
+ end
196
+ end
197
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ # Helpers for reading API payloads that may use either String or Symbol keys.
5
+ #
6
+ # Every `.from_hash` constructor in the SDK accepts both, since payloads
7
+ # arrive either parsed from JSON (String keys) or built in Ruby (Symbol keys).
8
+ # Spelling that lookup out inline as `data["k"] || data[:k] || default` adds
9
+ # two branches per field, which is what these helpers collapse.
10
+ #
11
+ # @api private
12
+ module HashAccess
13
+ module_function
14
+
15
+ # Read +key+ from +data+, accepting either a String or Symbol key.
16
+ #
17
+ # Falsey values fall through to +default+, matching the
18
+ # `data["k"] || data[:k] || default` idiom these helpers replace.
19
+ #
20
+ # @param data [Hash]
21
+ # @param key [String, Symbol]
22
+ # @param default [Object]
23
+ # @return [Object]
24
+ def value(data, key, default = nil)
25
+ data[key.to_s] || data[key.to_sym] || default
26
+ end
27
+
28
+ # Read +key+ and coerce it to a String. Returns +nil+ when the key is
29
+ # absent and no default is given.
30
+ #
31
+ # @return [String, nil]
32
+ def string(data, key, default = nil)
33
+ value(data, key, default)&.to_s
34
+ end
35
+
36
+ # Read +key+ and coerce it to an Integer.
37
+ #
38
+ # @return [Integer]
39
+ def integer(data, key, default = 0)
40
+ value(data, key, default).to_i
41
+ end
42
+
43
+ # Read +key+ as an Array, wrapping a bare value in one.
44
+ #
45
+ # @return [Array]
46
+ def array(data, key)
47
+ raw = value(data, key, [])
48
+ raw.is_a?(Array) ? raw : [raw]
49
+ end
50
+
51
+ # Read +key+, falling back to an empty Hash when absent.
52
+ #
53
+ # @return [Object]
54
+ def hash(data, key)
55
+ value(data, key, {})
56
+ end
57
+
58
+ # Extract the String values out of an attribute's +values+ list, which may
59
+ # hold either `{"value" => ...}` hashes or bare strings.
60
+ #
61
+ # @param data [Hash] the attribute hash
62
+ # @return [Array<String>]
63
+ def attribute_values(data)
64
+ array(data, :values).filter_map do |v|
65
+ case v
66
+ when Hash then string(v, :value)
67
+ when String then v
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ module Rails
5
+ # `zen_flags` and `feature_enabled?` helpers for controllers and views. The
6
+ # {Railtie} includes this in `ActionController::Base` and `ActionController::API`.
7
+ #
8
+ # If the controller has a `current_user`, flags are evaluated for a `user` context
9
+ # built from its `id` and, when it responds to it, `name`. Both are sent to
10
+ # Zenmanage with usage reports. Override the private `zenmanage_context` method to
11
+ # send something else.
12
+ #
13
+ # @example In a controller
14
+ # class ProductsController < ApplicationController
15
+ # def show
16
+ # @use_new_layout = feature_enabled?("new-layout")
17
+ # @checkout_variant = zen_flags.single("checkout-variant", "control").as_string
18
+ # end
19
+ # end
20
+ #
21
+ # @example Choosing the context
22
+ # class ApplicationController < ActionController::Base
23
+ # private
24
+ #
25
+ # def zenmanage_context
26
+ # return unless current_account
27
+ #
28
+ # Zenmanage::Context.single("organization", current_account.id.to_s)
29
+ # end
30
+ # end
31
+ #
32
+ # @example In a view
33
+ # <% if feature_enabled?("dark-mode") %>
34
+ # <%= render "dark_header" %>
35
+ # <% end %>
36
+ module ControllerHelpers
37
+ def self.included(base)
38
+ base.helper_method :zen_flags, :feature_enabled? if base.respond_to?(:helper_method)
39
+ end
40
+
41
+ # Returns a {FlagManager} scoped to the current request.
42
+ # If a Rack middleware has stored a FlagManager in the environment it will
43
+ # be reused; otherwise one is taken from the globally configured client.
44
+ #
45
+ # @return [FlagManager]
46
+ # @raise [ConfigurationError] if no client is configured
47
+ def zen_flags
48
+ @zen_flags ||= begin
49
+ manager = request.env[Middleware::ENV_KEY] || Zenmanage.flags
50
+ context = zenmanage_context
51
+ context ? manager.with_context(context) : manager
52
+ end
53
+ end
54
+
55
+ # Whether a boolean flag is on.
56
+ #
57
+ # @param key [String] flag key
58
+ # @param default [Boolean] returned when the flag can't be evaluated
59
+ # @return [Boolean]
60
+ def feature_enabled?(key, default: false)
61
+ zen_flags.single(key, default).enabled?
62
+ rescue Zenmanage::Error
63
+ default
64
+ end
65
+
66
+ private
67
+
68
+ # The context flags are evaluated against, or nil for none.
69
+ #
70
+ # @return [Zenmanage::Context, nil]
71
+ def zenmanage_context
72
+ return unless respond_to?(:current_user, true)
73
+
74
+ user = current_user
75
+ return unless user
76
+
77
+ Zenmanage::Context.new(
78
+ "user",
79
+ identifier: user.id.to_s,
80
+ name: user.respond_to?(:name) ? user.name : nil,
81
+ )
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ module Rails
5
+ # Rack middleware that makes a {FlagManager} available on the Rack environment.
6
+ # Controllers and views can use {Zenmanage::Rails::ControllerHelpers} to access
7
+ # it conveniently.
8
+ #
9
+ # The middleware is registered automatically via the {Railtie} when Rails is
10
+ # present. You can also insert it manually:
11
+ #
12
+ # @example Sinatra / plain Rack
13
+ # use Zenmanage::Rails::Middleware, Zenmanage::Client.new(config)
14
+ class Middleware
15
+ # Key under which the FlagManager is stored in the Rack environment.
16
+ ENV_KEY = "zenmanage.flags"
17
+
18
+ # @param app [#call] the next Rack application
19
+ # @param client [Zenmanage::Client, nil] the SDK client to use; defaults to the
20
+ # global {Zenmanage.client}, looked up on each request
21
+ def initialize(app, client = nil)
22
+ @app = app
23
+ @client = client
24
+ end
25
+
26
+ # @param env [Hash] Rack environment
27
+ def call(env)
28
+ client = @client || Zenmanage.client
29
+ env[ENV_KEY] = client.flags if client
30
+ @app.call(env)
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ module Rails
5
+ # Configure the global client from `config.zenmanage` and the `ZENMANAGE_*`
6
+ # environment variables, unless the app already called {Zenmanage.configure}.
7
+ #
8
+ # @param options [Hash{Symbol => Object}] settings as {Zenmanage.configure} takes them
9
+ # @raise [NameError] for a setting that doesn't exist
10
+ def self.auto_configure(options)
11
+ return if Zenmanage.client_configured?
12
+
13
+ Zenmanage.configure do |config|
14
+ options.each { |name, value| config[name] = value }
15
+ end
16
+ rescue ConfigurationError => e
17
+ ::Rails.logger&.warn("[Zenmanage] Skipping auto-configuration: #{e.message}")
18
+ end
19
+
20
+ # Railtie that integrates Zenmanage into Rails automatically.
21
+ #
22
+ # When the gem is loaded in a Rails app, this Railtie:
23
+ # 1. Configures the global client once the app's initializers have run, unless one
24
+ # of them already called {Zenmanage.configure}.
25
+ # 2. Registers the {Middleware} to make flags available on every request.
26
+ # 3. Includes {ControllerHelpers} into `ActionController::Base` and
27
+ # `ActionController::API`.
28
+ #
29
+ # Run `bin/rails generate zenmanage:install` for an initializer to start from.
30
+ #
31
+ # @example config/initializers/zenmanage.rb
32
+ # Zenmanage.configure do |config|
33
+ # config.environment_token = Rails.application.credentials.zenmanage_environment_token
34
+ # end
35
+ #
36
+ # @example config/application.rb
37
+ # config.zenmanage.cache_ttl = 300
38
+ class Railtie < ::Rails::Railtie
39
+ config.zenmanage = ActiveSupport::OrderedOptions.new
40
+
41
+ config.after_initialize do |app|
42
+ Zenmanage::Rails.auto_configure(app.config.zenmanage)
43
+ end
44
+
45
+ initializer "zenmanage.middleware" do |app|
46
+ app.middleware.use(Zenmanage::Rails::Middleware)
47
+ end
48
+
49
+ initializer "zenmanage.controller_helpers" do
50
+ ActiveSupport.on_load(:action_controller_base) do
51
+ include Zenmanage::Rails::ControllerHelpers
52
+ end
53
+
54
+ ActiveSupport.on_load(:action_controller_api) do
55
+ include Zenmanage::Rails::ControllerHelpers
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end