File: flexible_rollout.rb

package info (click to toggle)
ruby-unleash 3.2.5-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 252 kB
  • sloc: ruby: 1,098; makefile: 10; sh: 4
file content (55 lines) | stat: -rw-r--r-- 1,367 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
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
43
44
45
46
47
48
49
50
51
52
53
54
55
require 'unleash/strategy/util'

module Unleash
  module Strategy
    class FlexibleRollout < Base
      def name
        'flexibleRollout'
      end

      # need: params['percentage']
      def is_enabled?(params = {}, context = nil)
        return false unless params.is_a?(Hash)
        return false unless context.class.name == 'Unleash::Context'

        stickiness = params.fetch('stickiness', 'default')
        stickiness_id = resolve_stickiness(stickiness, context)

        begin
          percentage = Integer(params.fetch('rollout', 0))
          percentage = 0 if percentage > 100 || percentage.negative?
        rescue ArgumentError
          return false
        end

        group_id = params.fetch('groupId', '')
        normalized_number = Util.get_normalized_number(stickiness_id, group_id)

        return false if stickiness_id.nil?

        (percentage.positive? && normalized_number <= percentage)
      end

      private

      def random
        Random.rand(0..100)
      end

      def resolve_stickiness(stickiness, context)
        case stickiness
        when 'userId'
          context.user_id
        when 'sessionId'
          context.session_id
        when 'random'
          random
        when 'default'
          context.user_id || context.session_id || random
        else
          nil
        end
      end
    end
  end
end