Skip to content

Instantly share code, notes, and snippets.

@amkisko
Created March 3, 2025 10:30
Show Gist options
  • Save amkisko/b0794f4b49923e97c2415ff18a30d4a4 to your computer and use it in GitHub Desktop.
Save amkisko/b0794f4b49923e97c2415ff18a30d4a4 to your computer and use it in GitHub Desktop.
Remote Rails console user tracking & history management, console prompt to show commits-diff and environment
require "amazing_print"
AmazingPrint.pry!
app_id =
ENV["APP_ID"].presence ||
Rails.application.class.name.deconstantize.parameterize
app_env = ENV["ENVIRONMENT"].presence || Rails.env
commit_sha = ENV["GIT_COMMIT_SHA"]&.slice(0, 7)
commit_sha = `git rev-parse --short HEAD`.strip unless Rails.env.production?
remote_revision = ENV["REMOTE_REVISION"].presence
commit_mark = (remote_revision && commit_sha != remote_revision) ? "*" : ""
Pry.config.prompt_name = "#{app_id}-#{app_env}#{commit_sha ? "-#{commit_sha}#{commit_mark}" : ""}"
Pry.config.color = true
if app_env == "production"
Pry.config.prompt_name = Pry::Helpers::Text.red(Pry.config.prompt_name)
end
if ENV["REMOTE_USER_EMAIL"].present?
ActionReporter.context(console_user_email: ENV["REMOTE_USER_EMAIL"])
Current.user = RailsAdministrator.find_by(email: ENV["REMOTE_USER_EMAIL"])
end
if Current.user.present?
puts "Welcome to #{app_id} #{app_env} console, #{Current.user.email}!"
Pry.history.clear
Current.user.console_commands.order(created_at: :asc).pluck(:command).each do |command|
Pry.history.push(command)
end
Pry.config.hooks.add_hook(:after_eval, :record_commands) do |result, pry_instance|
Current.user.console_commands.create(command: pry_instance.input_ring.to_a.last)
end
elsif Rails.env.production?
puts "You are not authorized to access console, please request access to Rails console."
exit 1
end
class CreateRailsAdministrators < ActiveRecord::Migration[8.0]
def change
create_table :rails_administrators, id: :uuid do |t|
t.string :email, null: false, index: {unique: true}
t.string :password_digest, null: false
t.timestamps
end
end
end
class CreateRailsConsoleCommands < ActiveRecord::Migration[8.0]
def change
create_table :rails_console_commands, id: :uuid do |t|
t.references :rails_administrator, foreign_key: true, type: :uuid
t.text :command, null: false
t.timestamps
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment