Class: AutomationObject::Proxy::ThrottleProxy

Inherits:
Proxy
  • Object
show all
Defined in:
lib/automation_object/proxy/throttle_proxy.rb

Overview

Proxy class to throttle methods on the subject

Instance Method Summary collapse

Constructor Details

#initialize(subject) ⇒ ThrottleProxy

Returns a new instance of ThrottleProxy



9
10
11
# File 'lib/automation_object/proxy/throttle_proxy.rb', line 9

def initialize(subject)
  super
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_symbol, *args, &block) ⇒ Object



17
18
19
20
21
22
# File 'lib/automation_object/proxy/throttle_proxy.rb', line 17

def method_missing(method_symbol, *args, &block)
  start_time = Time.new.to_f
  execution_return = @subject.send(method_symbol, *args, &block)
  throttle_speed(method_symbol, start_time)
  execution_return
end

Instance Method Details

#add_method_throttle(method_symbol, time) ⇒ Object

Raises:

  • (ArgumentError)


24
25
26
27
28
29
30
31
32
# File 'lib/automation_object/proxy/throttle_proxy.rb', line 24

def add_method_throttle(method_symbol, time)
  raise ArgumentError, 'Expecting method_symbol argument to be a Symbol' unless method_symbol.is_a?(Symbol)

  raise ArgumentError, 'Expecting time argument to be Numeric' unless time.is_a?(Numeric)

  raise ArgumentError, "Expecting object to respond_to? #{method_symbol}" unless @subject.respond_to?(method_symbol)

  throttle_methods[method_symbol] = time
end

#delete_method_throttle(method_symbol) ⇒ Object

Delete throttle that exists

Parameters:

  • method_symbol (Symbol)

    method symbol to remove throttle from



36
37
38
# File 'lib/automation_object/proxy/throttle_proxy.rb', line 36

def delete_method_throttle(method_symbol)
  throttle_methods.delete(method_symbol)
end

#throttle_methodsObject



13
14
15
# File 'lib/automation_object/proxy/throttle_proxy.rb', line 13

def throttle_methods
  @throttle_methods ||= {}
end

#throttle_speed(method_symbol, start_time) ⇒ nil

Method to sleep the difference between actual and throttle time

Parameters:

  • method_symbol (Symbol)

    method that is to be throttled

  • start_time (Float)

    start time as float

Returns:

  • (nil)


44
45
46
47
48
49
50
# File 'lib/automation_object/proxy/throttle_proxy.rb', line 44

def throttle_speed(method_symbol, start_time)
  return unless throttle_methods.key?(method_symbol)
  total_time_taken = Time.new.to_f - start_time

  sleep_time = throttle_methods[method_symbol] - total_time_taken
  sleep(sleep_time) if sleep_time > 0
end