Class: Rack::Ping

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/ping.rb,
lib/rack/version.rb

Constant Summary collapse

VERSION =
"0.0.2"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) {|_self| ... } ⇒ Ping

Returns a new instance of Ping.

Yields:

  • (_self)

Yield Parameters:

  • _self (Rack::Ping)

    the object that the method was called on



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/rack/ping.rb', line 7

def initialize(app)
  @config = {
    :version => '0',
    :check_url => nil,
    :ok_regex => nil,
    :ok_text => 'ok',
    :ok_code => 200,
    :timeout_secs => 5,
    :error_text => 'error',
    :error_code => 500
  }

  yield self if block_given?
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



5
6
7
# File 'lib/rack/ping.rb', line 5

def config
  @config
end

Instance Method Details

#call(env) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rack/ping.rb', line 30

def call(env)
  if @check_block
    begin
      return @check_block.call() ? ok : error("logic")
    rescue
      return error("logic: #{$!}")
    end
  end

  if @config[:ok_regex] && @config[:check_url]
    begin
      timeout(@config[:timeout_secs]) do
        text = open(@config[:check_url]).read
        return error("regex") unless text =~ @config[:ok_regex]
      end
      rescue Timeout::Error
        return error("timeout")
      rescue
        return error("url: #{$!}")
    end
  end

  return ok
end

#check(&block) ⇒ Object



26
27
28
# File 'lib/rack/ping.rb', line 26

def check(&block)
  @check_block = block
end

#error(reason) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'lib/rack/ping.rb', line 55

def error(reason)
  [   @config[:error_code],
      NO_CACHE.merge({
        'Content-Type' => 'text/html',
        'x-app-version' => @config[:version],
        'x-ping-error'  => reason
      }),
      [@config[:error_text]]   ]
end

#okObject



65
66
67
68
69
70
71
72
# File 'lib/rack/ping.rb', line 65

def ok
  [   @config[:ok_code],
      NO_CACHE.merge({
        'Content-Type' => 'text/html',
        'x-app-version' => @config[:version]
      }),
      [@config[:ok_text]]   ]
end