pawurb / ruby-pg-extras

Ruby PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more.
MIT License
137 stars 11 forks source link

support tables as strings instead of putsing #9

Closed matti closed 2 years ago

matti commented 2 years ago

Thanks for this awesome gem - I made a quick monkey patch to puts to return strings so that the output can be caputered/displayed differently. I think this is valid usecase to implement properly in the gem.

RubyPGExtras.puts_returns_string = true
# now all table prints return uncolorized strings
module RubyPGExtras
  @@puts_returns_string = false

  def self.puts_returns_string
    @@puts_returns_string
  end

  def self.puts_returns_string=(value)
    @@puts_returns_string = value
  end
end

class String
  REGEXP_PATTERN = /\033\[([0-9]+);([0-9]+);([0-9]+)m(.+?)\033\[0m|([^\033]+)/m

  def uncolorize
    self.scan(REGEXP_PATTERN).inject("") do |str, match|
      str << (match[3] || match[4])
    end
  end
end

module RubyPGExtras
  def self.puts(args)
    if @@puts_returns_string
      args.to_s.uncolorize
    else
      Kernel.puts args
    end
  end
end

module RubyPGExtras
  class DiagnosePrint
    def puts(args)
      RubyPGExtras.puts args
    end
  end
end

module RubyPGExtras
  class TableInfoPrint
    def puts(args)
      RubyPGExtras.puts args
    end
  end
end

module RubyPGExtras
  class IndexInfoPrint
    def puts(args)
      RubyPGExtras.puts args
    end
  end
end
pawurb commented 2 years ago

Hi, thanks for an idea. But I'm not sure what's the use case? If you need output string to work with, why won't you use the JSON format?

Also this approach seems a bit complex. Maybe instead setting ENV["RUBY_PG_EXTRAS_NO_COLORS"] = true would disable the colorize method?

pawurb commented 2 years ago

Also, in addition to disabling colors with an ENV variable you could add a new in_format option e.g. ascii.

matti commented 2 years ago

I just want the table output as strings to be stored in files etc and not to spend time parsing json etc.

and my monkeypatch is not proposed implementation, just something I did fast.

matti commented 2 years ago

and another usecase is to for example have a sinatra etc route like

get "/table_info" do PgExtras.table_info end

again, much easier to output text instead of json+parse

matti commented 2 years ago

and, my monkeypatch is "that complex" because the pgextras code doesnt already have that ":ascii" format which would then be used by :table.

matti commented 2 years ago

like, instead, :table is formatting+puts in a one go, then it could be composer of :ascii+puts

anyway, just saying that pgextras could be refactored. I'm already good with my monkeypatch.

pawurb commented 2 years ago

Ok. I don't really see an urgent need for this feature, so if you don't feel like implementing it I'll close the issues for now.