71

I am writing a Ruby script for use in the Rails environment, but I chose to run it from irb because reloading the Rails console can be a pain. Now the wait time is much shorter from irb, but I'm bothered that I have to restart irb and require the script everytime I make a change. Is there a simpler way of reloading a script from irb?

I found a method in this thread, but that only applies to gem files apparently. My require statement looks like this

 require "#{File.expand_path(__FILE__)}/../lib/query"

EDIT: Having tried load rather than require, I still couldn't get it to work. I can't get a stop on these errors.

ruby-1.9.2-p0 > load "#{File.expand_path(__FILE__)}/../lib/query.rb"
LoadError: no such file to load -- /Users/newuser/Dropbox/Sites/rails/hacknyc/(irb)/../lib/query.rb
Community
  • 1
  • 1
picardo
  • 24,530
  • 33
  • 104
  • 151

4 Answers4

115

In irb, File.expand_path(__FILE__)} will just return "#{path you ran irb from}/(irb)". Which creates a path that doesn't actually exist. Luckily all file paths are relative to where you ran irb anyway. This means all you need is:

load "lib/query.rb"

If you want to use the __FILE__ in an actual file, that's fine, but don't expect it to produce a valid path in irb. Because an irb there is no "file" at all, so it cannot return valid path at all.

Also, __FILE__ will work fine if used in a file loaded into irb via load or require. Cause that's kinda what it's for.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
43

Instead of using require, try load. The former only loads a source file once, while the latter loads it every time you call it.

vonconrad
  • 25,227
  • 7
  • 68
  • 69
  • 1
    I tried load but it keeps complaining that it cannot find the file, and I did put the rb extension at the end of the line. – picardo Jan 08 '11 at 10:45
  • 1
    For reference, look at "Ruby Require VS Load VS Include VS Extend" -- http://ionrails.com/2009/09/19/ruby_require-vs-load-vs-include-vs-extend/ – Purplejacket Jun 01 '12 at 22:13
3

according to this link you need to load your file and do not forget the extention.

Here is a fancier version to use too at this link number 2 which could be helpful for you too.

You may want to try hashing out why your rails console isn't working for you though.

pjammer
  • 9,489
  • 5
  • 46
  • 56
  • Rails console is simply too slow to load. I tried `load` but it keeps complaining that it cannot find the file, and I did put the rb extension at the end of the line. – picardo Jan 08 '11 at 10:42
  • if this file is inside of your lib directory, then it's loaded and you can/should be able to use it, unless it pukes up errors on starting. To use it in another file, you just need to add `require NameOfModuleOrClass` (that is inside that query file), to one of the files in your rails app. – pjammer Jan 08 '11 at 14:02
1

I think load is what you are looking for.

lukad
  • 17,287
  • 3
  • 36
  • 53