Class: StayAwake::Strategies::NetHttp

Inherits:
Object
  • Object
show all
Includes:
Singleton, StayAwake::Strategy
Defined in:
lib/stay_awake/strategies/net_http.rb

Class Method Summary collapse

Methods included from StayAwake::Strategy

included

Class Method Details

.available?Boolean

Returns:

  • (Boolean)


6
7
8
9
10
11
12
13
14
# File 'lib/stay_awake/strategies/net_http.rb', line 6

def self.available?
  begin
    require 'net/http'
    require 'uri'
    true
  rescue LoadError
    false
  end
end

.buzz(url) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/stay_awake/strategies/net_http.rb', line 16

def self.buzz(url)
  require 'timeout'
  StayAwake.logger.info 'Starting buzzing using net/http.'

  @thread = Thread.new do
    loop do
      begin
        Timeout.timeout(30) do
          uuid = SecureRandom.uuid
          StayAwake.logger.debug "Starting HTTP Request (#{uuid})."
          
          uri = URI.parse(url)
          http = Net::HTTP.new(uri.host, uri.port)
          request_method = StayAwake.config.request_method.to_s.capitalize
          request_class = Kernel.const_get("Net::HTTP::#{request_method}")
          response = http.request(request_class.new(uri.request_uri))
          
          StayAwake.logger.debug "HTTP Response arrived (#{uuid})."
          # TODO: Failing request?
        end
      rescue Timeout::Error
        StayAwake.logger.error "HTTP Timeout Error after 30 seconds (#{uuid})."
      rescue StandardError => e
        StayAwake.logger.error e.message
      end

      sleep StayAwake.config.interval
    end
  end
end

.shut_offObject



47
48
49
50
51
# File 'lib/stay_awake/strategies/net_http.rb', line 47

def self.shut_off
  @thread.kill
  @thread = nil
  StayAwake.logger.info 'Stopped buzzing.'
end