Skip to content

Instantly share code, notes, and snippets.

@seanlerner
Last active March 11, 2022 16:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanlerner/092ce4caec301d758b524adbd715242a to your computer and use it in GitHub Desktop.
Save seanlerner/092ce4caec301d758b524adbd715242a to your computer and use it in GitHub Desktop.
Sean's Ruby Helpers
<<-HOW_TO_USE
Paste this line into any ruby console if you dare:
require 'net/http'; url = 'https://gist.githubusercontent.com/seanlerner/092ce4caec301d758b524adbd715242a/raw/seans-ruby-helpers.rb'; eval(Net::HTTP.get(URI(url)))
HOW_TO_USE
def exception_message(exception)
if exception.message.include?("undefined method `include'")
"Fail! Sean's Ruby Helpers must be invoked from `main` and not from within a method (e.g. trying to invoke while using binding.pry inside a method will not work)"
else
"Unhandled Error: #{exception}. Please post a comment with the details on the gist: https://gist.github.com/seanlerner/092ce4caec301d758b524adbd715242a"
end
end
begin
require 'active_support/all'
require 'action_view'
require 'csv'
require 'net/http'
include ActionView::Helpers::DateHelper
# BENCHMARK
def measure_execution_time
Benchmark.measure do
yield
end.real.round(1).to_s + " seconds"
end
# MEMORY
def memory_usage_mb
memory_in_kb = `ps -o rss -p #{$PROCESS_ID}`.chomp.split("\n").last.strip.to_i
memory_in_kb / 1024
end
def memory_usage_mb_to_s
"#{memory_usage_mb} MB"
end
# TERMINAL
def keep_alive
puts "Keeping Alive ... press control-c to interrupt"
seconds = 0
2.hours.to_i.times do
print "\rhello: #{seconds}"
sleep 1
seconds += 1
print "\rworld: #{seconds}"
sleep 1
seconds += 1
end
puts "Done"
end
# CSV
def csv_to_h(csv_path)
CSV.open(csv_path, headers: :first_row, header_converters: :symbol).map(&:to_h)
end
def array_to_csv(file_name, array)
headers = csv_line(array.first.keys)
lines = [headers] + array.map(&:values).map { |values| csv_line(values) }
File.write(file_name, lines.join("\n"))
end
def csv_line(values)
values = sanitize(values)
values.map { |value| %("#{value}")}.join(',')
end
def sanitize(values)
return values unless values.any? { |value| value.to_s.include?('"') }
puts %(WARNING! The following entry has a value with a double quote: #{values.join('|') })
values.map { |value| value.to_s.gsub('"', "'") }
end
# HASH DIFF
def hash_diff(hash_1, hash_2)
keys = (hash_1.keys + hash_2.keys).sort.uniq
print_line_diff('{', '{')
keys.each_with_index do |key, index|
comma = index + 1 < keys.count ? ',' : ''
key_str = key.inspect
value_1 = hash_1[key].inspect + comma
value_2 = hash_2[key].inspect + comma
print_line_diff(" #{key_str} => #{value_1}", " #{key_str} => #{value_2}")
end
print_line_diff('}', '}')
end
def print_line_diff(result_1, result_2)
screen_width = STDOUT.winsize.last
hash_2_column_start = screen_width / 2
spacing = result_1.ljust(hash_2_column_start - 1)[/ +$/]
yellow = "\e[1;33m"
reset = "\e[0;0m"
unless result_1 == result_2
result_1 = "#{yellow}#{result_1}#{reset}"
result_2 = "#{yellow}#{result_2}#{reset}"
end
puts result_1 + spacing + result_2
end
# HTTP
def get(url)
Net::HTTP.get(URI(url))
end
# INTERESTING METHODS
class Object
def im
interesting_methods
end
def interesting_methods
if self.class == Module
(singleton_methods + instance_methods).uniq.sort
else
(public_methods - Object.methods).sort
end
end
def self.interesting_methods
(public_methods - Object.methods).sort
end
end
# HELPER HELPERS
def ready
revisions_html = get('https://gist.github.com/seanlerner/092ce4caec301d758b524adbd715242a/revisions')
last_update = time_ago_in_words(revisions_html.scan(%r{datetime="(.+?)"}).first.first)
"Success! Sean's Ruby Helpers are ready to use. Last update #{last_update} ago."
end
# ALIASES
alias ka keep_alive
alias mb memory_usage_mb
alias mbs memory_usage_mb_to_s
alias me measure_execution_time
rescue StandardError => exception
@exception = exception_message(exception)
end
# Finished
@exception || ready
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment