Class: SiteHub::Collection::SplitRouteCollection

Inherits:
SiteHub::Collection show all
Defined in:
lib/sitehub/collection/split_route_collection.rb,
lib/sitehub/collection/split_route_collection/split.rb

Defined Under Namespace

Classes: InvalidSplitException, Split

Constant Summary collapse

FIXNUM_ERR_MSG =
'splits must be a Fixnum'.freeze
SPLIT_ERR_MSG =
'total split percentages can not be greater than 100%'.freeze
INVALID_SPILTS_MSG =
'splits do not add up to 100% and no default has been specified'.freeze
MAX =
100
MIN =
0

Instance Method Summary collapse

Methods inherited from SiteHub::Collection

inherited

Constructor Details

#initialize(hash = {}) ⇒ SplitRouteCollection

Returns a new instance of SplitRouteCollection.



15
16
17
18
19
# File 'lib/sitehub/collection/split_route_collection.rb', line 15

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

Instance Method Details

#[](key) ⇒ Object



39
40
41
# File 'lib/sitehub/collection/split_route_collection.rb', line 39

def [](key)
  key?(key) ? super(key).value : nil
end

#add(id, value, percentage) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/sitehub/collection/split_route_collection.rb', line 21

def add(id, value, percentage)
  raise InvalidSplitException, FIXNUM_ERR_MSG unless percentage.is_a?(Fixnum)
  upper_bound = lower_bound + percentage

  raise InvalidSplitException, SPLIT_ERR_MSG if upper_bound > MAX
  self[id] = Split.new(lower_bound, upper_bound, value)
end

#resolve(*args) ⇒ Object



29
30
31
32
33
# File 'lib/sitehub/collection/split_route_collection.rb', line 29

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

#transform(&block) ⇒ Object



35
36
37
# File 'lib/sitehub/collection/split_route_collection.rb', line 35

def transform(&block)
  values.each { |split| split.update_value(&block) }
end

#valid?Boolean

Returns:

  • (Boolean)


43
44
45
46
47
48
49
# File 'lib/sitehub/collection/split_route_collection.rb', line 43

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

  warn(INVALID_SPILTS_MSG)
  false
end