Last active
September 4, 2024 16:51
-
-
Save Drowze/5e70342a2845190a9e3e6f804f4a1877 to your computer and use it in GitHub Desktop.
My .irbrc - with some hacks here and there; definitely not something you'd want in a production environment!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# rubocop:disable Style/Documentation | |
IRB.conf[:SAVE_HISTORY] = 10_000 | |
alias r require | |
%w[json securerandom yaml pp pry pry-byebug redis zlib base64].each do |lib| | |
r lib | |
rescue LoadError | |
puts "couldnt load #{lib}" | |
nil | |
end | |
r 'csv' if Gem.loaded_specs['csv'] # avoid requiring if it's not in Gemfile, to avoid warnings | |
# forcely load a gem, even if it's not in the Gemfile | |
# probably won't work in every situation - and perhaps doing this isn't a great idea | |
# well it gets the job done | |
def __force_load(gem_name) # rubocop:disable Metrics | |
begin | |
require(gem_name) | |
return true | |
rescue LoadError | |
nil | |
end | |
paths = Dir[*ENV['GEM_PATH'].split(':').map { |path| "#{path}/gems/#{gem_name}-*/lib" }] | |
selected_path = paths.max_by { |path| Gem::Version.new(path[Regexp.new("#{gem_name}-([\\d.]+)/lib"), 1]) } | |
raise "Couldnt find #{gem_name} gem - is it installed?" unless selected_path | |
$LOAD_PATH << selected_path | |
begin | |
r gem_name | |
puts "forcely loaded #{gem_name}" | |
rescue LoadError => _e | |
warn "could not forcely load #{gem_name}" | |
end | |
end | |
# Uses Niceql to get a pretty SQL based on the caller. | |
# Will try to force load Niceql if needed | |
class Object | |
def pretty_sql(...) | |
return super if defined?(super) | |
__force_load('niceql') unless defined?(Niceql) | |
sql = if respond_to?(:to_sql) | |
to_sql | |
elsif is_a?(String) | |
self | |
else | |
raise 'No valid sql' | |
end | |
puts Niceql::Prettifier.prettify_sql(sql) | |
end | |
end | |
# Copy a string to the clipboard (and returns the string) | |
class Object | |
def pbcopy(input = nil) | |
input ||= is_a?(String) ? self : inspect | |
prog = RUBY_PLATFORM.match?(/darwin/) ? 'pbcopy' : 'xclip' | |
IO.popen(prog, 'w') { |f| f << input } | |
input | |
end | |
end | |
# Add some copy helpers to common classes | |
class Hash; def pbcopy = super(JSON.pretty_generate(self)); end | |
class Array; def pbcopy = super(JSON.pretty_generate(self)); end | |
# Opinated benchmark helper | |
def bm(times = 100, &block) | |
return unless block_given? | |
require 'benchmark' | |
label = "#{times} runs" | |
Benchmark.benchmark(Benchmark::CAPTION, label.length - 1, Benchmark::FORMAT, 'avg:') do |bm| | |
total = bm.report(label) { times.times(&block) } | |
[total / times] | |
end | |
end | |
# Execute a command and captures its output, then return it | |
def capture_stdout | |
return unless block_given? | |
original_stdout = $stdout | |
$stdout = StringIO.new | |
yield | |
$stdout.string | |
ensure | |
$stdout = original_stdout | |
end | |
# Get some lovely string to paste in Kibana console. Useful to debug some Elasticsearch queries | |
def kibana(input) | |
input = input.render unless input.is_a?(Hash) | |
<<~ELASTICSEARCH.pbcopy | |
GET /#{input[:index].first}/_search | |
#{JSON.pretty_generate(input[:body])} | |
ELASTICSEARCH | |
end | |
# Caller stacktrace, with some opinated filtering applied | |
def _caller(exclude_gems = false) # rubocop:disable Style/OptionalBooleanParameter | |
ignored = %w[/pry/ /byebug/ /rspec/ /irb/ /lib/irb.rb <internal:kernel> /bin/rspec \(irb\):\d] | |
result = caller | |
.reject { _1.match? Regexp.new(ignored.join('|')) } | |
.map { _1.gsub("#{ENV['GEM_HOME']}/gems/", '$GEM_HOME/').gsub(ENV['PWD'], '$PWD') } | |
return result unless exclude_gems | |
result.reject { _1.start_with?('$GEM_HOME/') } | |
end | |
# List out all the available `let(...)` definitions, along with their source location | |
def _let_space # rubocop:disable Metrics | |
return [] unless is_a?(RSpec::Core::ExampleGroup) | |
public_methods.filter_map do |met| | |
met_method = method(met) | |
file, line = method(met).source_location | |
next if file.nil? | |
# this file didn't change in 3 years, so the line number is stable enough | |
next unless file.end_with?('lib/rspec/core/memoized_helpers.rb') | |
next unless line == 343 | |
file, line = met_method.super_method.source_location | |
let_definition = Pathname.new(file).relative_path_from(Dir.pwd).to_s + ":#{line}" | |
let_definition = "./#{let_definition}" unless let_definition.match?(%r{^\.+/}) | |
[met, let_definition] | |
end.to_h | |
end | |
# List out all available fixtures, as defined by AnyFixture | |
def _fixtures(klass = nil) | |
store = TestProf::AnyFixture.send(:cache).store | |
return store unless klass | |
store.select { |_, v| v.is_a?(klass) } | |
end | |
# Get schema of a hash/array | |
def get_schema(obj) # rubocop:disable Metrics | |
if obj.is_a?(Hash) | |
obj.transform_values { |v| get_schema(v) } | |
elsif obj.is_a?(Array) | |
obj.map { |v| get_schema(v) }.uniq.sort { |a, b| a.to_s <=> b.to_s } | |
elsif obj.is_a?(String) && Integer(obj, exception: false) | |
Integer | |
elsif obj.is_a?(String) && Float(obj, exception: false) | |
Float | |
else | |
obj.class | |
end | |
end | |
(def t = true) unless defined?(t) | |
(def f = false) unless defined?(f) | |
# rubocop:enable Style/Documentation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment