Skip to content

Instantly share code, notes, and snippets.

@alebian
Created March 18, 2020 12:56
Show Gist options
  • Save alebian/607f73f6579723091d1fa77abdaeb8e7 to your computer and use it in GitHub Desktop.
Save alebian/607f73f6579723091d1fa77abdaeb8e7 to your computer and use it in GitHub Desktop.
# Helper classes
class String
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
end
def red
colorize(31)
end
def green
colorize(32)
end
def yellow
colorize(33)
end
def blue
colorize(34)
end
def light_blue
colorize(36)
end
end
class Object
def local_methods
(methods - Object.instance_methods).sort
end
end
# IRB config
require 'irb/completion'
require 'irb/ext/save-history'
IRB.conf[:SAVE_HISTORY] = 100
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"
IRB.conf[:AUTO_INDENT] = true
# Define Rails console
def app_prompt
rails_klass = Rails.application.class
app = rails_klass.respond_to?(:module_parent) ? rails_klass.module_parent : rails_klass.parent
"#{app.name}".light_blue
end
def env_prompt
case Rails.env
when 'development' then 'development'.green
when 'production' then 'production'.red
else
"#{Rails.env}".yellow
end
end
if defined?(Rails)
IRB.conf[:PROMPT] ||= {}
prompt = "#{app_prompt}[#{env_prompt}]:%03n"
IRB.conf[:PROMPT][:RAILS] = {
:PROMPT_I => "#{prompt}> ",
:PROMPT_N => "#{prompt}> ",
:PROMPT_S => "#{prompt}* ",
:PROMPT_C => "#{prompt}? ",
:RETURN => " => %s\n"
}
IRB.conf[:PROMPT_MODE] = :RAILS
end
# History config
def get_line(line_number)
Readline::HISTORY[line_number]
end
def print_line(line_number, show_line_numbers = true)
print "[%04d] " % line_number if show_line_numbers
puts get_line(line_number)
end
def history(how_many = 50)
history_size = Readline::HISTORY.size
return puts 'No history' if history_size == 0
start_index = 0
if history_size <= how_many
how_many = history_size - 1
end_index = how_many - 1
else
end_index = history_size - 1
start_index = end_index - how_many
end
start_index.upto(end_index) { |n| print_line(n) }
nil
end
def get_lines(lines = [])
return [get_line(lines)] if lines.is_a?(Fixnum) || lines.is_a?(Integer)
out = []
lines = lines.to_a if lines.is_a?(Range)
lines.each do |line|
out << get_line(line)
end
return out
end
def irb_eval(lines)
to_eval = get_lines(lines)
eval to_eval.join("\n")
to_eval.each { |line| Readline::HISTORY << line }
end
def history_do(lines = Readline::HISTORY.size - 2)
irb_eval(lines)
nil
end
# Aliases
alias :q :exit
alias :h :history
alias :h! :history_do
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment