This is great for creating reproducible examples when reporting bugs, quick projects and experimentation.

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"
  gem "activerecord"
  gem "sqlite3"
end

require "active_record"
require "logger"

ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :fruits, force: true do |t|
  end
end

class Fruit < ActiveRecord::Base
end

You can also combine this will rspec:

# test.rb

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"
  gem "rspec"
end

require "rspec/autorun"

RSpec.describe 'fruit' do
end

Now you can just to ruby test.rb and the gems will install and specs run.

Combine this with entr so the file is run on code change:

echo test.rb | entr -c -r ruby test.rb