Skip to content

Instantly share code, notes, and snippets.

@cookrn
Created May 27, 2016 17:00
Show Gist options
  • Select an option

  • Save cookrn/885e45acb07f7cce51caaa70c34bab98 to your computer and use it in GitHub Desktop.

Select an option

Save cookrn/885e45acb07f7cce51caaa70c34bab98 to your computer and use it in GitHub Desktop.

Revisions

  1. cookrn created this gist May 27, 2016.
    42 changes: 42 additions & 0 deletions screenfetched.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    #!/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
    }