Module: SL::Util
- Defined in:
- lib/searchlink/util.rb
Overview
Utilities
Class Method Summary collapse
-
.cache_file_for(filename) ⇒ String
Get the path for a cache file.
-
.exec_with_timeout(cmd, timeout) ⇒ String
Execute system command with deadman’s switch.
-
.search_with_timeout(search, timeout) ⇒ Array
Execute a search with deadman’s switch.
Class Method Details
.cache_file_for(filename) ⇒ String
Get the path for a cache file
83 84 85 86 87 |
# File 'lib/searchlink/util.rb', line 83 def cache_file_for(filename) cache_folder = File.('~/.config/searchlink/cache') FileUtils.mkdir_p(cache_folder) unless File.directory?(cache_folder) File.join(cache_folder, filename.sub(/(\.cache)?$/, '.cache')) end |
.exec_with_timeout(cmd, timeout) ⇒ String
Execute system command with deadman’s switch
<stackoverflow.com/questions/8292031/ruby-timeouts-and-system-commands> <stackoverflow.com/questions/12189904/fork-child-process-with-timeout-and-capture-output>
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 46 47 48 |
# File 'lib/searchlink/util.rb', line 17 def exec_with_timeout(cmd, timeout) begin # stdout, stderr pipes rout, wout = IO.pipe rerr, werr = IO.pipe stdout, stderr = nil pid = Process.spawn(cmd, pgroup: true, out: wout, err: werr) Timeout.timeout(timeout) do Process.waitpid(pid) # close write ends so we can read from them wout.close werr.close stdout = rout.readlines.join stderr = rerr.readlines.join end rescue Timeout::Error Process.kill(-9, pid) Process.detach(pid) ensure wout.close unless wout.closed? werr.close unless werr.closed? # dispose the read ends of the pipes rout.close rerr.close end stdout&.strip end |
.search_with_timeout(search, timeout) ⇒ Array
Execute a search with deadman’s switch
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/searchlink/util.rb', line 58 def search_with_timeout(search, timeout) url = nil title = nil link_text = nil begin Timeout.timeout(timeout) do url, title, link_text = search.call end rescue Timeout::Error SL.add_error('Timeout', 'Search timed out') url, title, link_text = false end [url, title, link_text] end |