Skip to content

Instantly share code, notes, and snippets.

@cookrn
Created May 27, 2016 17:00
Show Gist options
  • Save cookrn/885e45acb07f7cce51caaa70c34bab98 to your computer and use it in GitHub Desktop.
Save cookrn/885e45acb07f7cce51caaa70c34bab98 to your computer and use it in GitHub Desktop.
An easy way to cache `screenfetch` results for a set amount of time so that every new terminal doesn't re-run it
#!/usr/bin/env ruby
if fetched_file_blank? or fetched_file_expired?
fetch!
end
write_cached_screenfetch!
BEGIN {
COMMAND = 'screenfetch'.freeze
EXPIRATION_TIMEOUT = 5 * 60 # 5 minutes
FETCHED_PATH = File.expand_path('~/.screenfetched').freeze
WRITE_MODE = 'w'.freeze
def fetch!
File.open(FETCHED_PATH, WRITE_MODE) do |f|
if f.flock(File::LOCK_EX|File::LOCK_NB)
f.write(`#{COMMAND}`)
f.flush
else
f.flock(File::LOCK_EX)
end
f.flock(File::LOCK_UN)
end
end
def fetched_file_blank?
!File.exist?(FETCHED_PATH)
end
def fetched_file_expired?
Time.now - File.mtime(FETCHED_PATH) > EXPIRATION_TIMEOUT
end
def write_cached_screenfetch!
File.open(FETCHED_PATH) do |f|
f.flock(File::LOCK_SH)
puts(f.read)
end
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment