Class: Allocate

Inherits:
Object show all
Defined in:
lib/guerrilla_patch/allocate.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(amount = 0, ratios = []) ⇒ Allocate

Returns a new instance of Allocate.



5
6
7
8
# File 'lib/guerrilla_patch/allocate.rb', line 5

def initialize(amount = 0 , ratios = [])
  @amount = amount
  @ratios = ratios
end

Instance Attribute Details

#amountObject

Returns the value of attribute amount.



2
3
4
# File 'lib/guerrilla_patch/allocate.rb', line 2

def amount
  @amount
end

#ratiosObject

Returns the value of attribute ratios.



3
4
5
# File 'lib/guerrilla_patch/allocate.rb', line 3

def ratios
  @ratios
end

Class Method Details

.evenly(amount, number_of_slices) ⇒ Object



26
27
28
29
30
31
# File 'lib/guerrilla_patch/allocate.rb', line 26

def self.evenly(amount, number_of_slices)
  Allocate.new.tap do |a|
    a.amount = amount
    a.ratios = (1..number_of_slices).map { 1.to_d/number_of_slices }
  end.divided
end

Instance Method Details

#compensate_last_slice(rates) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/guerrilla_patch/allocate.rb', line 16

def compensate_last_slice(rates)
  rates.tap do |rates|
    max_rate = rates.max.abs
    rates[-1] = (rates[-1] + (amount - rates.sum_me)).round(2)
    if  rates[-1].abs > (2 * max_rate.abs )
      raise "Number is too small to be allocated on that number of slices(#@amount on #{@ratios.size} slices)."
    end
  end
end

#dividedObject



10
11
12
13
14
# File 'lib/guerrilla_patch/allocate.rb', line 10

def divided
  divided_ratios = @ratios.map { |ratio| ratio.to_d/ratios.sum_me.to_d }
  rates = divided_ratios.map { |ratio| ((@amount * ratio).round(2)) }
  compensate_last_slice(rates)
end