Skip to content

Instantly share code, notes, and snippets.

@jmmastey
Last active January 29, 2021 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmmastey/e957b7e55b18a8d181a4cb88a5831fa3 to your computer and use it in GitHub Desktop.
Save jmmastey/e957b7e55b18a8d181a4cb88a5831fa3 to your computer and use it in GitHub Desktop.
# Put this code (or whatever part is useful) in a file in your
# home directory called `~/.pryrc`. Then, every time you load
# a pry console, this code will automatically be executed, giving
# you these tools! I write a lot of little scripts this way.
# see `ar_counts` below
class ArCounter
def initialize
@last_count = 0
@current_count = 0
subscribe
end
def subscribe
puts "Subscribing to active record counts"
ActiveSupport::Notifications.subscribe("sql.active_record") do
@current_count += 1
end
end
def report
diff = @current_count - @last_count
puts "Current count is #{@current_count}, last count was #{@last_count}"
puts "#{diff} queries since last count"
@last_count = @current_count
diff
end
end
# Call this method once before you execute your code and it will
# add hooks to ActiveRecord. Then call it again to display how
# many queries have been executed since last invocation. You
# can do this over and over, and even `reload!` in between
def ar_counts(force: false)
$ar_counter = nil if force
$ar_counter ||= ArCounter.new
$ar_counter.report
end
# allows you to use FactoryBot.create(:blah) in development consoles
def load_factories
require 'factory_bot'
FactoryBot.find_definitions
include FactoryBot::Syntax::Methods
if defined? Rails
Dir[Rails.root.join("spec/support/**/*.rb")].each { |file| require file rescue NameError }
end
puts 'Loaded factories, syntax helpers, and support files if available!'
end
# change to your username, but allows you to find your own user in
# a console trivially.
def me
User.find 5975067
end
# if you generate e.g. a large CSV worth of data and want to open
# it within a textfile (maybe to copy/paste elsewhere, or just to save),
# passing it into this method will open it in TextEdit. also plays nicely
# with arrays of strings.
require 'tempfile'
def textpad(str, prefix = "textpad")
str = Array(str).join("\n")
file = Tempfile.new(prefix)
file.write str
file.close
`open #{file.path}`
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment