Sha256: ebaced5886168f3efe1391dfa0a77b641815ece28b35aa59e100ffed60249b0b

Contents?: true

Size: 1.04 KB

Versions: 9

Compression:

Stored size: 1.04 KB

Contents

require "crc32"

module Shamu
  module Features
    module Conditions

      # Match against a limited percentage of total users.
      class Percentage < Conditions::Condition

        # (see Condition#match?)
        def match?( context )
          if context.user_id
            ( user_id_hash( context.user_id ) ^ toggle_crc ) % 100 < percentage
          else
            context.sticky!
            Random.rand( 100 ) < percentage
          end
        end

        private

          def percentage
            @percentage ||= [ config.to_i, 100 ].min
          end

          def user_id_hash( user_id )
            if user_id.is_a?( Numeric )
              return user_id
            else
              return user_id.sub( "-", "" ).to_i( 16 )
            end
          end

          def toggle_crc
            # Use the name of the toggle to provide consistent semi-random noise
            # into the user selection process.
            @toggle_crc ||= Crc32.calculate( toggle.name, toggle.name.length, 0 )
          end

      end

    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
shamu-0.0.13 lib/shamu/features/conditions/percentage.rb
shamu-0.0.11 lib/shamu/features/conditions/percentage.rb
shamu-0.0.9 lib/shamu/features/conditions/percentage.rb
shamu-0.0.8 lib/shamu/features/conditions/percentage.rb
shamu-0.0.7 lib/shamu/features/conditions/percentage.rb
shamu-0.0.5 lib/shamu/features/conditions/percentage.rb
shamu-0.0.4 lib/shamu/features/conditions/percentage.rb
shamu-0.0.3 lib/shamu/features/conditions/percentage.rb
shamu-0.0.2 lib/shamu/features/conditions/percentage.rb