Class: Variation::Profile

Inherits:
Object
  • Object
show all
Defined in:
lib/variation/profile.rb

Overview

Represent a setting that can change over time.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hashed_args) ⇒ Profile

Returns a new instance of Profile.



8
9
10
11
12
13
14
15
16
# File 'lib/variation/profile.rb', line 8

def initialize hashed_args
  raise HashedArgMissingError unless hashed_args.has_key?(:start_value)
  changes = hashed_args[:changes] || {}

  @start_value = hashed_args[:start_value]
  @changes = changes
  
  trim_changes_if_needed @changes
end

Instance Attribute Details

#changesObject (readonly)

Returns the value of attribute changes.



6
7
8
# File 'lib/variation/profile.rb', line 6

def changes
  @changes
end

#start_valueObject (readonly)

Returns the value of attribute start_value.



6
7
8
# File 'lib/variation/profile.rb', line 6

def start_value
  @start_value
end

Instance Method Details

#at(x) ⇒ Object



98
99
100
# File 'lib/variation/profile.rb', line 98

def at(x)
  function.call(x)
end

#data(step_size) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
# File 'lib/variation/profile.rb', line 102

def data(step_size)
  data = {}
  if @changes.any?
    f = function
    domain = (@changes.keys.max - length)..length
    domain.step(step_size) do |x|
      data[x] = f.call(x)
    end
  end
  return data
end

#end_valueObject

end

Profile.new(@start_value, changes)

end



57
58
59
60
61
62
63
# File 'lib/variation/profile.rb', line 57

def end_value
  if @changes.any?
    @changes[@changes.keys.max].end_value
  else
    start_value
  end
end

#functionObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/variation/profile.rb', line 65

def function
  functions = {}

  prev_val = start_value
  prev_offset = -Float::INFINITY

  if @changes.any?
    sorted_offsets = @changes.keys.sort

    sorted_offsets.each_index do |i|
      offset = sorted_offsets[i]
      change = @changes[offset]
      start_of_transition = offset - change.length

      unless prev_offset == start_of_transition
        functions[prev_offset...start_of_transition] = ConstantFunction.from_value(prev_val)
      end
      functions[start_of_transition...offset] = change.transition_function([start_of_transition, prev_val])

      prev_val = change.end_value
      prev_offset = offset
    end
  end

  functions[prev_offset...Float::INFINITY] = ConstantFunction.from_value(prev_val)

  lambda do |x|
    result = functions.find {|domain,func| domain.include?(x) }
    f = result[1]
    f.call(x)
  end
end

#lengthObject



18
19
20
21
22
23
24
25
26
# File 'lib/variation/profile.rb', line 18

def length
  length = 0
  if @changes.any?
    first_offset = @changes.keys.min
    last_offset = @changes.keys.max
    length = (last_offset - first_offset) + @changes[first_offset].length
  end
  return length
end