1
0

subscriber.rb 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # frozen_string_literal: true
  2. require 'active_support/subscriber'
  3. module Docs
  4. class Subscriber < ActiveSupport::Subscriber
  5. cattr_accessor :namespace
  6. def self.subscribe_to(notifier)
  7. attach_to(namespace, new, notifier)
  8. end
  9. private
  10. delegate :puts, :print, :tty?, to: :$stdout
  11. def log(msg)
  12. puts "\r" + justify(msg)
  13. end
  14. def format_url(url)
  15. url.to_s.remove %r{\Ahttps?://}
  16. end
  17. def format_path(path)
  18. path.to_s.remove File.join(File.expand_path('.'), '')
  19. end
  20. def justify(str)
  21. return str unless terminal_width
  22. str = str.dup
  23. max_length = if tag = str.slice!(/ \[.+\]\z/)
  24. terminal_width - tag.length
  25. else
  26. terminal_width
  27. end
  28. str.truncate(max_length).ljust(max_length) << tag.to_s
  29. end
  30. def terminal_width
  31. return @terminal_width if defined? @terminal_width
  32. @terminal_width = if !tty?
  33. nil
  34. elsif ENV['COLUMNS']
  35. ENV['COLUMNS'].to_i
  36. else
  37. `stty size`.scan(/\d+/).last.to_i
  38. end
  39. rescue
  40. @terminal_width = nil
  41. end
  42. end
  43. end