Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

irb

I am currently editing a file, and I'm using irb to test the api:

> require './file.rb'
> o = Object.new
> o.method

I then want to be able to edit the file.rb, and be able to see changes immediately. Example: assume new_method did not exist when I first required file.rb:

> o.new_method

Which will return an error. Is there a sandbox/developer mode or a method whereby I can achieve the above without having to reload the file every time? Require will not work after the first require, regardless. I assume worst case I'd have to use load instead.

like image 460
Damien Roche Avatar asked Jun 13 '12 18:06

Damien Roche


People also ask

How do I load a Ruby file in IRB?

From the main menu, choose Tools | Load file/selection into IRB/Rails console.

What happens when you require a file in Ruby?

In Ruby, the require method is used to load another file and execute all its statements. This serves to import all class and method definitions in the file.

What is IRB command used for?

IRB stands for “interactive Ruby” and is a tool to interactively execute Ruby expressions read from the standard input. The irb command from your shell will start the interpreter.


2 Answers

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).

like image 136
bta Avatar answered Oct 22 '22 01:10

bta


This won't run every command, but you can include a file on every IRb session. ~/.irbrc is loaded each time you start an IRb session.

~/.irbrc

require "~/somefile.rb"

~/somefile.rb

puts "somefile loaded"

terminal

> irb
somefile loaded
irb(main):001:0> 

~/.irbrc is loaded each time you start an irb session

like image 28
maček Avatar answered Oct 21 '22 23:10

maček