Can You 'Require' Ruby File in Irb Session, Automatically, on Every Command

Can you 'require' ruby file in irb session, automatically, on every command?

I usually create a simple function like this:

def reload
load 'myscript.rb'
# Load any other necessary files here ...
end

With that, a simple reload will re-import all of the scripts that I'm working on. It's not automatic, but it's the closest thing that I've been able to come up with.

You may be able to override method_missing to call this function automatically when your object is invoked with a method that doesn't exist. I've never tried it myself, though, so I can't give any specific advice. It also wouldn't help if you're calling a method that already exists but has simply been modified.

In my own laziness, I've gone as far as mapping one of the programmable buttons on my mouse to the key sequence "reload<enter>". When I'm using irb, all it takes is the twitch of a pinky finger to reload everything. Consequently when I'm not using irb, I end up with the string "reload" inserted in documents unintentionally (but that's a different problem entirely).

IRb: how to start an interactive ruby session with pre-loaded classes

I'm not sure it's possible to 'flush' a session. However, you can load your classes like this:

irb -r 'hello.rb' -r 'hello_objects.rb'

How to create custom IRB file to load a Ruby project's files, gems and dependencies?

Very simple, actually:

#!/usr/bin/env ruby
require "bundler/setup"
# ...
# everything else you need
# ...
require "irb"
IRB.start

When you start IRB using IRB.start, you will have available everything that's been loaded/initialised before it.

Require a lib directory in irb console

Create a file named .irbrc in your home directory, and write require commands for whatever file you want to require in there. When you run irb, .irbrc will be loaded.

How would I have irb require the config/boot.rb file from the directory I run irb in?

I would do:

 config_file = File.join(Dir.pwd, 'config', 'boot.rb')
require config_file if File.exist?(config_file)

automatically load project's environment to irb

Your project should have one file which loads the environment. Assuming your project is in lib/project.rb then simply:

$ irb -Ilib -rproject

frequently flush irb history to file

Having hacked on irb many a time, good luck with a clean solution. Instead I'd recommend ripl, an irb alternative. By default it saves history more intelligently (i.e. even when you abruptly exit out with Control-D).

If you want to write history after every command, it's easy with ripl since it's built to be extended with plugins:

# add to your ~/.riplrc
module Ripl::ImmediateHistory
# write to history after every eval
def eval_input(input)
super
File.open(history_file, 'a') {|f| f.puts input }
end

# disable writing to history when ripl exits
def write_history; end
end
Ripl::Shell.send :include, Ripl::ImmediateHistory


Related Topics



Leave a reply



Submit