Class: Magick::Feature

Inherits:
Object
  • Object
show all
Defined in:
lib/magick/feature.rb

Constant Summary collapse

VALID_TYPES =
%i[boolean string number].freeze
VALID_STATUSES =
%i[active inactive deprecated].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, adapter_registry, **options) ⇒ Feature

Returns a new instance of Feature.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/magick/feature.rb', line 14

def initialize(name, adapter_registry, **options)
  @name = name.to_s
  @adapter_registry = adapter_registry
  @type = (options[:type] || :boolean).to_sym
  @status = (options[:status] || :active).to_sym
  @default_value = options.fetch(:default_value, default_for_type)
  @description = options[:description]
  @display_name = options[:name] || options[:display_name]
  @group = options[:group]
  @targeting = {}
  @dependencies = options[:dependencies] ? Array(options[:dependencies]) : []
  @stored_value_initialized = false # Track if @stored_value has been explicitly set

  # Performance optimizations: cache expensive checks
  @_targeting_empty = true # Will be updated after load_from_adapter
  @_rails_events_enabled = false # Cache Rails events availability (only enable in dev)
  @_perf_metrics_enabled = false # Cache performance metrics (disabled by default for speed)

  validate_type!
  validate_default_value!
  load_from_adapter
  # Update targeting empty cache after loading
  @_targeting_empty = @targeting.empty?
  # Cache performance metrics availability (check once, not on every call)
  # Only enable if performance_metrics exists AND is actually being used
  @_perf_metrics_enabled = !Magick.performance_metrics.nil?
  # Save description and display_name to adapter if they were provided and not already in adapter
  
end

Instance Attribute Details

#adapter_registryObject (readonly)

Returns the value of attribute adapter_registry.



12
13
14
# File 'lib/magick/feature.rb', line 12

def adapter_registry
  @adapter_registry
end

#default_valueObject (readonly)

Returns the value of attribute default_value.



12
13
14
# File 'lib/magick/feature.rb', line 12

def default_value
  @default_value
end

#descriptionObject (readonly)

Returns the value of attribute description.



12
13
14
# File 'lib/magick/feature.rb', line 12

def description
  @description
end

#display_nameObject (readonly)

Returns the value of attribute display_name.



12
13
14
# File 'lib/magick/feature.rb', line 12

def display_name
  @display_name
end

#groupObject (readonly)

Returns the value of attribute group.



12
13
14
# File 'lib/magick/feature.rb', line 12

def group
  @group
end

#nameObject (readonly)

Returns the value of attribute name.



12
13
14
# File 'lib/magick/feature.rb', line 12

def name
  @name
end

#statusObject (readonly)

Returns the value of attribute status.



12
13
14
# File 'lib/magick/feature.rb', line 12

def status
  @status
end

#typeObject (readonly)

Returns the value of attribute type.



12
13
14
# File 'lib/magick/feature.rb', line 12

def type
  @type
end

Instance Method Details

#add_dependency(dependency_name) ⇒ Object



414
415
416
417
418
419
420
421
422
423
424
# File 'lib/magick/feature.rb', line 414

def add_dependency(dependency_name)
  @dependencies ||= []
  @dependencies << dependency_name.to_s unless @dependencies.include?(dependency_name.to_s)

  # Rails 8+ event
  if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
    Magick::Rails::Events.dependency_added(name, dependency_name)
  end

  true
end

#check_enabled(context = {}) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/magick/feature.rb', line 92

def check_enabled(context = {})
  # Dup context to avoid mutating the caller's hash
  context = context.dup

  # Extract context from user object if provided
  # This allows Magick.enabled?(:feature, user: player) to work
  if context[:user]
    extracted = extract_context_from_object(context.delete(:user))
    # Merge extracted context, but don't override explicit values already in context
    extracted.each do |key, value|
      context[key] = value unless context.key?(key)
    end
  end

  # Fast path: check status first
  return false if status == :inactive
  return false if status == :deprecated && !context[:allow_deprecated]

  # Fast path: skip targeting checks if targeting is empty (most common case)
  unless @_targeting_empty
    # Check exclusions FIRST — exclusions always take priority over inclusions
    return false if excluded?(context)

    # Check date/time range targeting
    return false if targeting[:date_range] && !date_range_active?(targeting[:date_range])

    # Check IP address targeting
    return false if targeting[:ip_address] && context[:ip_address] && !ip_address_matches?(context[:ip_address])

    # Check custom attributes
    return false if targeting[:custom_attributes] && !custom_attributes_match?(context,
                                                                               targeting[:custom_attributes])

    # Check complex conditions
    return false if targeting[:complex_conditions] && !complex_conditions_match?(context,
                                                                                 targeting[:complex_conditions])

    # Check user/group/role/percentage targeting
    targeting_result = check_targeting(context)
    return false if targeting_result.nil?
    # Targeting doesn't match - return false

    # Targeting matches - for boolean features, return true directly
    # For string/number features, still check the value
    return true if type == :boolean
    # For string/number, continue to check value below

  end

  # Get value and check based on type
  value = get_value(context)
  case type
  when :boolean
    value == true
  when :string
    !value.nil? && value != ''
  when :number
    value.to_f.positive?
  else
    false
  end
rescue StandardError => e
  # Return false on any error (fail-safe)
  warn "Magick: Error in check_enabled for '#{name}': #{e.message}" if defined?(Rails) && Rails.env.development?
  false
end

#deleteObject



611
612
613
614
615
616
617
618
619
# File 'lib/magick/feature.rb', line 611

def delete
  adapter_registry.delete(name)
  @stored_value = nil
  @stored_value_initialized = false # Reset initialization flag so get_value returns default_value
  @targeting = {}
  # Also remove from Magick.features if registered
  Magick.features.delete(name.to_s)
  true
end

#dependenciesObject



437
438
439
# File 'lib/magick/feature.rb', line 437

def dependencies
  @dependencies || []
end

#disable(user_id: nil) ⇒ Object



554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/magick/feature.rb', line 554

def disable(user_id: nil)
  # Clear all targeting to disable globally
  @targeting = {}
  save_targeting

  case type
  when :boolean
    set_value(false, user_id: user_id)
  when :string
    set_value('', user_id: user_id)
  when :number
    set_value(0, user_id: user_id)
  else
    raise InvalidFeatureValueError, "Cannot disable feature of type #{type}"
  end

  # Ensure registered feature instance also has targeting cleared
  if Magick.features.key?(name)
    registered = Magick.features[name]
    registered.instance_variable_set(:@targeting, {})
  end

  # Cascade disable: disable all features that depend on this one
  disable_dependent_features(user_id: user_id)

  # Rails 8+ event
  if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
    Magick::Rails::Events.feature_disabled_globally(name, user_id: user_id)
  end

  true
end

#disable_custom_attribute(attribute_name) ⇒ Object



389
390
391
392
393
394
395
396
397
398
# File 'lib/magick/feature.rb', line 389

def disable_custom_attribute(attribute_name)
  custom_attrs = targeting[:custom_attributes] || {}
  custom_attrs.delete(attribute_name.to_sym)
  if custom_attrs.empty?
    disable_targeting(:custom_attributes)
  else
    enable_targeting(:custom_attributes, custom_attrs)
  end
  true
end

#disable_date_rangeObject



367
368
369
370
# File 'lib/magick/feature.rb', line 367

def disable_date_range
  disable_targeting(:date_range)
  true
end

#disable_for_group(group_name) ⇒ Object



245
246
247
248
# File 'lib/magick/feature.rb', line 245

def disable_for_group(group_name)
  disable_targeting(:group, group_name)
  true
end

#disable_for_role(role_name) ⇒ Object



255
256
257
258
# File 'lib/magick/feature.rb', line 255

def disable_for_role(role_name)
  disable_targeting(:role, role_name)
  true
end

#disable_for_tag(tag_name) ⇒ Object



265
266
267
268
# File 'lib/magick/feature.rb', line 265

def disable_for_tag(tag_name)
  disable_targeting(:tag, tag_name)
  true
end

#disable_for_user(user_id) ⇒ Object



235
236
237
238
# File 'lib/magick/feature.rb', line 235

def disable_for_user(user_id)
  disable_targeting(:user, user_id)
  true
end

#disable_ip_addressesObject



377
378
379
380
# File 'lib/magick/feature.rb', line 377

def disable_ip_addresses
  disable_targeting(:ip_address)
  true
end

#disable_percentage_of_requestsObject



357
358
359
360
# File 'lib/magick/feature.rb', line 357

def disable_percentage_of_requests
  disable_targeting(:percentage_requests)
  true
end

#disable_percentage_of_usersObject



337
338
339
340
# File 'lib/magick/feature.rb', line 337

def disable_percentage_of_users
  disable_targeting(:percentage_users)
  true
end

#disabled?(context = {}) ⇒ Boolean

Returns:

  • (Boolean)


159
160
161
# File 'lib/magick/feature.rb', line 159

def disabled?(context = {})
  !enabled?(context)
end

#disabled_for?(object, **additional_context) ⇒ Boolean

Returns:

  • (Boolean)


171
172
173
# File 'lib/magick/feature.rb', line 171

def disabled_for?(object, **additional_context)
  !enabled_for?(object, **additional_context)
end

#enable(user_id: nil) ⇒ Object



514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'lib/magick/feature.rb', line 514

def enable(user_id: nil)
  # Check if this feature is a dependency of any disabled features
  # If a main feature that depends on this feature is disabled, prevent enabling this dependency
  # Dependencies cannot be enabled until the main feature is enabled
  dependent_features = find_dependent_features
  disabled_dependents = dependent_features.select do |dep_feature_name|
    dep_feature = Magick.features[dep_feature_name.to_s] || Magick[dep_feature_name]
    # Check if the dependent feature (main feature) is disabled
    dep_feature && !dep_feature.enabled?
  end

  unless disabled_dependents.empty?
    # Return false if any main feature that depends on this feature is disabled
    # This prevents enabling a dependency when the main feature is disabled
    return false
  end

  # Clear all targeting to enable globally
  @targeting = {}
  save_targeting

  case type
  when :boolean
    set_value(true, user_id: user_id)
  when :string
    raise InvalidFeatureValueError, 'Cannot enable string feature. Use set_value instead.'
  when :number
    raise InvalidFeatureValueError, 'Cannot enable number feature. Use set_value instead.'
  else
    raise InvalidFeatureValueError, "Cannot enable feature of type #{type}"
  end

  # Rails 8+ event
  if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
    Magick::Rails::Events.feature_enabled_globally(name, user_id: user_id)
  end

  true
end

#enable_for_custom_attribute(attribute_name, values, operator: :equals) ⇒ Object



382
383
384
385
386
387
# File 'lib/magick/feature.rb', line 382

def enable_for_custom_attribute(attribute_name, values, operator: :equals)
  custom_attrs = targeting[:custom_attributes] || {}
  custom_attrs[attribute_name.to_sym] = { values: Array(values), operator: operator }
  enable_targeting(:custom_attributes, custom_attrs)
  true
end

#enable_for_date_range(start_date, end_date) ⇒ Object



362
363
364
365
# File 'lib/magick/feature.rb', line 362

def enable_for_date_range(start_date, end_date)
  enable_targeting(:date_range, { start: start_date, end: end_date })
  true
end

#enable_for_group(group_name) ⇒ Object



240
241
242
243
# File 'lib/magick/feature.rb', line 240

def enable_for_group(group_name)
  enable_targeting(:group, group_name)
  true
end

#enable_for_ip_addresses(ip_addresses) ⇒ Object



372
373
374
375
# File 'lib/magick/feature.rb', line 372

def enable_for_ip_addresses(ip_addresses)
  enable_targeting(:ip_address, Array(ip_addresses))
  true
end

#enable_for_role(role_name) ⇒ Object



250
251
252
253
# File 'lib/magick/feature.rb', line 250

def enable_for_role(role_name)
  enable_targeting(:role, role_name)
  true
end

#enable_for_tag(tag_name) ⇒ Object



260
261
262
263
# File 'lib/magick/feature.rb', line 260

def enable_for_tag(tag_name)
  enable_targeting(:tag, tag_name)
  true
end

#enable_for_user(user_id) ⇒ Object



230
231
232
233
# File 'lib/magick/feature.rb', line 230

def enable_for_user(user_id)
  enable_targeting(:user, user_id)
  true
end

#enable_percentage_of_requests(percentage) ⇒ Object



342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/magick/feature.rb', line 342

def enable_percentage_of_requests(percentage)
  @targeting[:percentage_requests] = percentage.to_f
  save_targeting

  # Update registered feature instance if it exists
  Magick.features[name].instance_variable_set(:@targeting, @targeting.dup) if Magick.features.key?(name)

  # Rails 8+ event
  if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
    Magick::Rails::Events.targeting_added(name, targeting_type: :percentage_requests, targeting_value: percentage)
  end

  true
end

#enable_percentage_of_users(percentage) ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/magick/feature.rb', line 322

def enable_percentage_of_users(percentage)
  @targeting[:percentage_users] = percentage.to_f
  save_targeting

  # Update registered feature instance if it exists
  Magick.features[name].instance_variable_set(:@targeting, @targeting.dup) if Magick.features.key?(name)

  # Rails 8+ event
  if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
    Magick::Rails::Events.targeting_added(name, targeting_type: :percentage_users, targeting_value: percentage)
  end

  true
end

#enabled?(context = {}) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/magick/feature.rb', line 44

def enabled?(context = {})
  # Check performance metrics dynamically (in case enabled after feature creation)
  # But cache the check result for performance
  perf_metrics = Magick.performance_metrics
  perf_metrics_enabled = !perf_metrics.nil?

  # Update cached flag if it changed
  @_perf_metrics_enabled = perf_metrics_enabled if @_perf_metrics_enabled != perf_metrics_enabled

  # Fast path: if performance metrics disabled, skip all overhead
  return check_enabled(context) unless perf_metrics_enabled

  # Performance metrics enabled: measure and record
  # Use inline timing to avoid function call overhead
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  result = check_enabled(context)
  duration = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000 # milliseconds

  # Record metrics (fast path - minimal overhead)
  perf_metrics.record(name, 'enabled?', duration, success: true)

  # Rails 8+ events (only in development or when explicitly enabled)
  if @_rails_events_enabled
    if result
      Magick::Rails::Events.feature_enabled(name, context: context)
    else
      Magick::Rails::Events.feature_disabled(name, context: context)
    end
  end

  # Warn if deprecated (only if enabled)
  if status == :deprecated && result && !context[:allow_deprecated] && Magick.warn_on_deprecated
    warn "DEPRECATED: Feature '#{name}' is deprecated and will be removed."
    Magick::Rails::Events.deprecated_warning(name) if @_rails_events_enabled
  end

  result
rescue StandardError => e
  # Record error metrics if enabled
  if perf_metrics_enabled && perf_metrics
    duration = defined?(start_time) && start_time ? (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000 : 0.0
    perf_metrics.record(name, 'enabled?', duration, success: false)
  end
  # Return false on any error (fail-safe)
  warn "Magick: Error checking feature '#{name}': #{e.message}" if defined?(Rails) && Rails.env.development?
  false
end

#enabled_for?(object, **additional_context) ⇒ Boolean

Returns:

  • (Boolean)


163
164
165
166
167
168
169
# File 'lib/magick/feature.rb', line 163

def enabled_for?(object, **additional_context)
  # Extract context from object
  context = extract_context_from_object(object)
  # Merge with any additional context provided
  context.merge!(additional_context)
  enabled?(context)
end

#exclude_group(group_name) ⇒ Object



292
293
294
295
# File 'lib/magick/feature.rb', line 292

def exclude_group(group_name)
  enable_targeting(:excluded_groups, group_name)
  true
end

#exclude_ip_addresses(ip_addresses) ⇒ Object



312
313
314
315
# File 'lib/magick/feature.rb', line 312

def exclude_ip_addresses(ip_addresses)
  enable_targeting(:excluded_ip_addresses, Array(ip_addresses))
  true
end

#exclude_role(role_name) ⇒ Object



302
303
304
305
# File 'lib/magick/feature.rb', line 302

def exclude_role(role_name)
  enable_targeting(:excluded_roles, role_name)
  true
end

#exclude_tag(tag_name) ⇒ Object



282
283
284
285
# File 'lib/magick/feature.rb', line 282

def exclude_tag(tag_name)
  enable_targeting(:excluded_tags, tag_name)
  true
end

#exclude_user(user_id) ⇒ Object

— Exclusion methods —



272
273
274
275
# File 'lib/magick/feature.rb', line 272

def exclude_user(user_id)
  enable_targeting(:excluded_users, user_id)
  true
end

#get_value(context = {}) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/magick/feature.rb', line 179

def get_value(context = {})
  # Fast path: check targeting rules first (only if targeting exists)
  unless @_targeting_empty
    targeting_result = check_targeting(context)
    # If targeting matches (returns truthy), return the stored value
    # If targeting doesn't match (returns nil), continue to return default value
    unless targeting_result.nil?
      # Targeting matches - return stored value (or load it if not initialized)
      return @stored_value if @stored_value_initialized

      # Load from adapter
      loaded_value = load_value_from_adapter
      if loaded_value.nil?
        # Value not found in adapter, use default and cache it
        @stored_value = default_value
        @stored_value_initialized = true
        return default_value
      else
        # Value found in adapter, use it and mark as initialized
        @stored_value = loaded_value
        @stored_value_initialized = true
        return loaded_value
      end

    end
    # Targeting doesn't match - return default value
    return default_value
  end

  # Fast path: use cached value if initialized (avoid adapter calls)
  return @stored_value if @stored_value_initialized

  # Load from adapter if instance variable hasn't been initialized
  loaded_value = load_value_from_adapter
  if loaded_value.nil?
    # Value not found in adapter, use default and cache it
    @stored_value = default_value
    @stored_value_initialized = true
    default_value
  else
    # Value found in adapter, use it and mark as initialized
    @stored_value = loaded_value
    @stored_value_initialized = true
    loaded_value
  end
rescue StandardError => e
  # Return default value on error (fail-safe)
  warn "Magick: Error in get_value for '#{name}': #{e.message}" if defined?(Rails) && Rails.env.development?
  default_value
end

#get_variant(context = {}) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/magick/feature.rb', line 441

def get_variant(context = {})
  return nil unless targeting[:variants]

  variants = targeting[:variants]
  selected_variant = if variants.length == 1
                       variants.first[:name]
                     else
                       # Weighted random selection
                       total_weight = variants.sum { |v| v[:weight] || 0 }
                       if total_weight.zero?
                         variants.first[:name]
                       else
                         random = rand(total_weight)
                         current = 0
                         selected = nil
                         variants.each do |variant|
                           current += variant[:weight] || 0
                           if random < current
                             selected = variant[:name]
                             break
                           end
                         end
                         selected || variants.first[:name]
                       end
                     end

  # Rails 8+ event
  if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
    Magick::Rails::Events.variant_selected(name, variant_name: selected_variant, context: context)
  end

  selected_variant
end

#reloadObject

Reload feature state from adapter (useful when feature is changed externally)



622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
# File 'lib/magick/feature.rb', line 622

def reload
  load_from_adapter
  # Update targeting empty cache
  @_targeting_empty = @targeting.empty?
  # Update performance metrics flag (in case it was enabled after feature creation)
  @_perf_metrics_enabled = !Magick.performance_metrics.nil?
  # Update registered feature instance if it exists
  if Magick.features.key?(name)
    registered = Magick.features[name]
    registered.instance_variable_set(:@stored_value, @stored_value)
    registered.instance_variable_set(:@stored_value_initialized, @stored_value_initialized)
    registered.instance_variable_set(:@status, @status)
    registered.instance_variable_set(:@description, @description)
    registered.instance_variable_set(:@display_name, @display_name)
    registered.instance_variable_set(:@group, @group)
    registered.instance_variable_set(:@targeting, @targeting.dup)
    registered.instance_variable_set(:@_targeting_empty, @_targeting_empty)
    registered.instance_variable_set(:@_perf_metrics_enabled, @_perf_metrics_enabled)
  end
  true
end

#remove_dependency(dependency_name) ⇒ Object



426
427
428
429
430
431
432
433
434
435
# File 'lib/magick/feature.rb', line 426

def remove_dependency(dependency_name)
  @dependencies&.delete(dependency_name.to_s)

  # Rails 8+ event
  if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
    Magick::Rails::Events.dependency_removed(name, dependency_name)
  end

  true
end

#remove_group_exclusion(group_name) ⇒ Object



297
298
299
300
# File 'lib/magick/feature.rb', line 297

def remove_group_exclusion(group_name)
  disable_targeting(:excluded_groups, group_name)
  true
end

#remove_ip_exclusionObject



317
318
319
320
# File 'lib/magick/feature.rb', line 317

def remove_ip_exclusion
  disable_targeting(:excluded_ip_addresses)
  true
end

#remove_role_exclusion(role_name) ⇒ Object



307
308
309
310
# File 'lib/magick/feature.rb', line 307

def remove_role_exclusion(role_name)
  disable_targeting(:excluded_roles, role_name)
  true
end

#remove_tag_exclusion(tag_name) ⇒ Object



287
288
289
290
# File 'lib/magick/feature.rb', line 287

def remove_tag_exclusion(tag_name)
  disable_targeting(:excluded_tags, tag_name)
  true
end

#remove_user_exclusion(user_id) ⇒ Object



277
278
279
280
# File 'lib/magick/feature.rb', line 277

def remove_user_exclusion(user_id)
  disable_targeting(:excluded_users, user_id)
  true
end

#save_targetingObject



657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
# File 'lib/magick/feature.rb', line 657

def save_targeting
  # Save targeting to adapter (this updates memory synchronously, then Redis/AR)
  # The set method already publishes cache invalidation to other processes via Pub/Sub
  adapter_registry.set(name, 'targeting', targeting)

  # Update the feature in Magick.features if it's registered
  if Magick.features.key?(name)
    Magick.features[name].instance_variable_set(:@targeting, targeting.dup)
    # Update targeting empty cache for performance
    Magick.features[name].instance_variable_set(:@_targeting_empty, targeting.empty?)
  end

  # Update local targeting empty cache for performance
  @_targeting_empty = targeting.empty?

  # NOTE: We don't need to explicitly publish cache invalidation here because:
  # 1. adapter_registry.set already publishes cache invalidation (synchronously for async Redis updates)
  # 2. Publishing twice causes duplicate reloads in other processes
  # 3. The set method handles both sync and async Redis updates correctly
end

#set_group(group_name) ⇒ Object



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/magick/feature.rb', line 595

def set_group(group_name)
  if group_name.nil? || group_name.to_s.strip.empty?
    @group = nil
    # Clear group from adapter by setting to empty string (adapters handle this)
    adapter_registry.set(name, 'group', nil)
  else
    @group = group_name.to_s.strip
    adapter_registry.set(name, 'group', @group)
  end

  # Update registered feature instance if it exists
  Magick.features[name].instance_variable_set(:@group, @group) if Magick.features.key?(name)

  true
end

#set_status(new_status) ⇒ Object



587
588
589
590
591
592
593
# File 'lib/magick/feature.rb', line 587

def set_status(new_status)
  raise InvalidFeatureValueError, "Invalid status: #{new_status}" unless VALID_STATUSES.include?(new_status.to_sym)

  @status = new_status.to_sym
  adapter_registry.set(name, 'status', status)
  true
end

#set_value(value, user_id: nil) ⇒ Object



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/magick/feature.rb', line 475

def set_value(value, user_id: nil)
  old_value = @stored_value
  validate_value!(value)

  # Bulk write all metadata in a single adapter call instead of 7 separate calls
  data = { 'value' => value, 'type' => type, 'status' => status, 'default_value' => default_value }
  data['description'] = description if description
  data['display_name'] = display_name if display_name
  data['group'] = group if group
  adapter_registry.set_all_data(name, data)

  @stored_value = value
  @stored_value_initialized = true

  # Update registered feature instance if it exists
  if Magick.features.key?(name)
    registered = Magick.features[name]
    registered.instance_variable_set(:@stored_value, value)
    registered.instance_variable_set(:@stored_value_initialized, true)
    registered.instance_variable_set(:@targeting, @targeting.dup) if @targeting
  end

  changes = { value: { from: old_value, to: value } }

  Magick.audit_log&.log(
    name,
    'set_value',
    user_id: user_id,
    changes: changes
  )

  if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
    Magick::Rails::Events.feature_changed(name, changes: changes, user_id: user_id)
    Magick::Rails::Events.audit_logged(name, action: 'set_value', user_id: user_id, changes: changes)
  end

  true
end

#set_variants(variants) ⇒ Object



400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/magick/feature.rb', line 400

def set_variants(variants)
  variants_array = Array(variants).map do |v|
    v.is_a?(FeatureVariant) ? v : FeatureVariant.new(v[:name], v[:value], weight: v[:weight] || 0)
  end
  enable_targeting(:variants, variants_array.map(&:to_h))

  # Rails 8+ event
  if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
    Magick::Rails::Events.variant_set(name, variants: variants_array)
  end

  true
end

#to_hObject



644
645
646
647
648
649
650
651
652
653
654
655
# File 'lib/magick/feature.rb', line 644

def to_h
  {
    name: name,
    display_name: display_name,
    type: type,
    status: status,
    value: stored_value,
    default_value: default_value,
    description: description,
    targeting: targeting
  }
end

#value(context = {}) ⇒ Object



175
176
177
# File 'lib/magick/feature.rb', line 175

def value(context = {})
  get_value(context)
end