class VertexClient::Utils::AdjustmentAllocator

Constants

ADJUSTMENT_ERROR
WEIGHTS_ERROR

Attributes

adjustment[R]
weights[R]

Public Class Methods

new(adjustment, weights) click to toggle source
# File lib/vertex_client/utils/adjustment_allocator.rb, line 4
def initialize(adjustment, weights)
  @adjustment = adjustment
  @weights    = weights
end

Public Instance Methods

allocate() click to toggle source
# File lib/vertex_client/utils/adjustment_allocator.rb, line 9
def allocate
  return [] if weights.empty? && @adjustment.zero?
  validate!
  allocations, remainders = allocations_with_remainders.transpose
  remaining_adjustment    = adjustment_in_cents - allocations.sum
  deserving_indices       = remainders.each_with_index.sort_by { |remainder, i| [remainder, i] }.map { |_r, i| i }.last(remaining_adjustment)
  allocations.each_with_index.map { |allocation, i| deserving_indices.include?(i) ? cents_to_dollars(allocation + 1) : cents_to_dollars(allocation) }
end

Private Instance Methods

adjustment_format_valid?() click to toggle source
# File lib/vertex_client/utils/adjustment_allocator.rb, line 23
def adjustment_format_valid?
  adjustment.is_a?(Numeric) && (dollars_to_cents(adjustment) == adjustment * 100)
end
adjustment_in_cents() click to toggle source
# File lib/vertex_client/utils/adjustment_allocator.rb, line 27
def adjustment_in_cents
  dollars_to_cents(adjustment)
end
allocations_with_remainders() click to toggle source
# File lib/vertex_client/utils/adjustment_allocator.rb, line 31
def allocations_with_remainders
  weights.map do |weight|
    (adjustment_in_cents * weight).divmod(weights_total)
  end
end
cents_to_dollars(cents) click to toggle source
# File lib/vertex_client/utils/adjustment_allocator.rb, line 37
def cents_to_dollars(cents)
  cents / 100.to_d
end
dollars_to_cents(dollars) click to toggle source
# File lib/vertex_client/utils/adjustment_allocator.rb, line 41
def dollars_to_cents(dollars)
  (dollars * 100).to_i
end
validate!() click to toggle source
# File lib/vertex_client/utils/adjustment_allocator.rb, line 45
def validate!
  raise VertexClient::ValidationError.new(ADJUSTMENT_ERROR) unless adjustment_format_valid?
  raise VertexClient::ValidationError.new(WEIGHTS_ERROR) unless weights_format_valid?
end
weights_format_valid?() click to toggle source
# File lib/vertex_client/utils/adjustment_allocator.rb, line 50
def weights_format_valid?
  weights.all? { |weight| weight.is_a?(Numeric) && weight >= 0 } && !weights_total.zero?
end
weights_total() click to toggle source
# File lib/vertex_client/utils/adjustment_allocator.rb, line 54
def weights_total
  weights.sum
end