Class: Estimator::Estimate

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

Constant Summary collapse

LAST_ESTIMATE_EMPTY_STRING =
'last estimate is empty'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ Estimate

TODO: handle file better



13
14
15
16
17
# File 'lib/estimator.rb', line 13

def initialize( file_path )
    @file_path = file_path
    @values = {}
    @last_estimate = LAST_ESTIMATE_EMPTY_STRING
end

Instance Attribute Details

#file_pathObject (readonly)

Returns the value of attribute file_path.



10
11
12
# File 'lib/estimator.rb', line 10

def file_path
  @file_path
end

#last_estimateObject (readonly)

Returns the value of attribute last_estimate.



9
10
11
# File 'lib/estimator.rb', line 9

def last_estimate
  @last_estimate
end

#valuesObject (readonly)

Returns the value of attribute values.



8
9
10
# File 'lib/estimator.rb', line 8

def values
  @values
end

Instance Method Details

#add_value(value, time = nil) ⇒ Object



37
38
39
40
# File 'lib/estimator.rb', line 37

def add_value( value, time = nil )
    time = Time.now if time.nil?
    @values[value] = time
end

#estimateObject

TODO: Moving Averages en.wikipedia.org/wiki/Moving_average



44
45
46
47
48
49
50
51
52
# File 'lib/estimator.rb', line 44

def estimate
    return 'add more values before estimating' unless @values.count > 1
    # y = ax+b
    b = @values.keys.sort.last
    y = @values.keys.sort.first
    x = @values[y] - @values[b]
    a = (y-b)/x
    @last_estimate = @values[b] + (-b/a)
end

#load(file_path = @file_path) ⇒ Object



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

def load( file_path = @file_path )
    # TODO: change to exception?
    return nil unless File.exists?( file_path )
    # TODO: check for exception
    yaml_file      = YAML.load_file( file_path )
    @values        = yaml_file.fetch( :values, {} )
    @last_estimate = yaml_file.fetch( :last_estimate, LAST_ESTIMATE_EMPTY_STRING )
end

#save!Object



28
29
30
31
32
33
34
35
# File 'lib/estimator.rb', line 28

def save!
    File.open( @file_path, 'w' ) do |f|
        f.write( {
            values: @values,
            last_estimate: @last_estimate
        }.to_yaml )
    end
end