Sha256: 9a58a2d8ed0a5f1c4ebcf282c2ca72ca89bc1e3f03dfa1013fdbed0aa73e3081

Contents?: true

Size: 1.33 KB

Versions: 2

Compression:

Stored size: 1.33 KB

Contents

require_relative '../collection'
require_relative 'split_route_collection/split'
class SiteHub
  class Collection < Hash
    class SplitRouteCollection < Collection
      class InvalidSplitException < Exception;
      end

      def initialize(hash={})
        hash.each do |value, percentage|
          add(value.id, value, percentage)
        end
      end

      def add id, value, percentage
        raise InvalidSplitException, 'splits must be a Fixnum' unless percentage.is_a?(Fixnum)
        lower = values.last ? values.last.upper : 0
        upper = lower + percentage

        raise InvalidSplitException, 'total split percentages can not be greater than 100%' if upper > 100
        self[id] = Split.new(lower, upper, value)
      end

      def resolve(*args)
        random = rand(100)
        result = values.find { |split| random >= split.lower && random < split.upper }
        result ? result.value : nil
      end

      def transform &block
        values.each do |split|
          split.value = block.call(split.value)
        end
      end

      def [] key
        result = super
        result && result.value
      end

      def valid?
        last = values.last
        return true if last && last.upper == 100

        warn('splits do not add up to 100% and no default has been specified')
        false
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sitehub-0.4.2 lib/sitehub/collection/split_route_collection.rb
sitehub-0.4.1 lib/sitehub/collection/split_route_collection.rb