Skip to content

Instantly share code, notes, and snippets.

@carlzulauf
Created February 9, 2020 05:33
Show Gist options
  • Save carlzulauf/90b2a5f4b821c8177af9cd8ec25c0c0c to your computer and use it in GitHub Desktop.
Save carlzulauf/90b2a5f4b821c8177af9cd8ec25c0c0c to your computer and use it in GitHub Desktop.
IRB/Pry customizations
require 'pp'
# Enable mapping an array of hashes by key: hashes.map[:key]
Enumerator.send(:define_method, :[]) { |key| map { |obj| obj[key] } }
def r
begin
require 'redis' unless defined?(Redis)
begin
Redis.current.tap(&:info) # needed to know if connection failed
rescue
Redis.current = Redis.new(:path => "/tmp/redis.sock")
end
rescue LoadError
puts "redis gem not found"
end
end
# table print
def tp(table)
widths = table.first.map(&:to_s).map(&:length)
# find max length for each column
table.each do |row|
row.each_with_index do |cell, i|
widths[i] = [cell.to_s.length, widths[i]].max
end
end
# print table
table.each_with_index do |row, i|
cols = [].tap do |c|
row.each_with_index do |cell, n|
c << cell.to_s.ljust(widths[n])
end
end
puts cols.join(" | ")
puts widths.map {|l| "-" * l }.join("-|-") if i == 0
end
nil
end
def tz
ActiveSupport::TimeZone["US/Pacific"]
end
if defined?(ActiveRecord::Base)
class AR
class << self
def e(sql)
ActiveRecord::Base.connection.execute(sql).to_a
end
def silent(&blk)
with_log nil, &blk
end
def with_log(path = nil)
old_logger = ActiveRecord::Base.logger
begin
logger = path ? Logger.new(path) : nil
ActiveRecord::Base.logger = logger
yield
ensure
ActiveRecord::Base.logger = old_logger
end
File.size(path) if path
end
end
end
class ActiveRecord::Base
def self.sample
s = scoped
c = s.count
s.offset(rand(c)).first
end
def self.e(sql)
execute(sql).to_a
end
end
end
def show_ops(name = "Rate")
sample_length = 1.0
loop do
start_at = Time.now
stop_at = start_at + sample_length
count = 0
loop do
yield
count += 1
break if Time.now > stop_at
end
elapsed = Time.now - start_at
print "\r#{name}: #{(count / elapsed).round(2)} ops/sec"
end
end
def truncate_tables
whitelist = %w(spatial_ref_sys schema_migrations)
(ActiveRecord::Base.connection.tables - whitelist).each do |table|
ActiveRecord::Base.connection.truncate(table)
end
end
load File.join(File.expand_path("~"), ".irbrc")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment