File: process_title_updater.rb

package info (click to toggle)
ruby-spring 1.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 364 kB
  • ctags: 429
  • sloc: ruby: 2,762; makefile: 6
file content (65 lines) | stat: -rw-r--r-- 1,233 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
module Spring
  # Yes, I know this reimplements a bunch of stuff in Active Support, but
  # I don't want the spring client to depend on AS, in order to keep its
  # load time down.
  class ProcessTitleUpdater
    SECOND = 1
    MINUTE = 60
    HOUR   = 60*60

    def self.run(&block)
      updater = new(&block)

      Thread.new {
        $0 = updater.value
        loop { $0 = updater.next }
      }
    end

    attr_reader :block

    def initialize(start = Time.now, &block)
      @start = start
      @block = block
    end

    def interval
      distance = Time.now - @start

      if distance < MINUTE
        SECOND
      elsif distance < HOUR
        MINUTE
      else
        HOUR
      end
    end

    def next
      sleep interval
      value
    end

    def value
      block.call(distance_in_words)
    end

    def distance_in_words(now = Time.now)
      distance = now - @start

      if distance < MINUTE
        pluralize(distance, "sec")
      elsif distance < HOUR
        pluralize(distance / MINUTE, "min")
      else
        pluralize(distance / HOUR, "hour")
      end
    end

    private

    def pluralize(amount, unit)
      "#{amount.to_i} #{amount.to_i == 1 ? unit : "#{unit}s"}"
    end
  end
end