Module: Cukunity::Utils

Instance Method Summary collapse

Instance Method Details

#check_timeout(max_time, delay = 0.1) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'lib/cukunity/utils.rb', line 5

def check_timeout(max_time, delay = 0.1)
  start = Time.now
  until yield
    if (Time.now > (start + max_time))
      return true
    end
    sleep delay
  end
  false
end

#merge_options(options, defaults = {}) ⇒ Object



26
27
28
# File 'lib/cukunity/utils.rb', line 26

def merge_options(options, defaults = {})
  to_options(defaults).merge(to_options(options))
end

#restrict_options(options, *restricted_keys) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/cukunity/utils.rb', line 30

def restrict_options(options, *restricted_keys)
  restricted_keys = restricted_keys.map do |key|
    (key.to_sym rescue key) || key
  end
  to_options(options).delete_if do |key, value|
    !restricted_keys.include?(key)
  end
end

#to_options(hash) ⇒ Object

adapted from Rails



17
18
19
20
21
22
23
24
# File 'lib/cukunity/utils.rb', line 17

def to_options(hash)
  raise "Expected a hash but got a #{hash.class}" unless hash.instance_of? Hash
  hash_dup = hash.dup
  hash_dup.keys.each do |key|
    hash_dup[(key.to_sym rescue key) || key] = hash_dup.delete(key)
  end
  hash_dup
end

#wait_connectivity(host, port, max_time) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/cukunity/utils.rb', line 39

def wait_connectivity(host, port, max_time)
  begin
    Timeout::timeout(max_time) do
      begin
        s = TCPSocket.new(host, port)
        s.close
        true
      rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
        sleep 0.1
        retry
      end
    end
  rescue Timeout::Error
    false
  end
end