12

I recently found you can run an arbitrary Ruby file in the Rails console using load or require, as in:

load 'test_code.rb'

This is great as far as it goes, but using either load or require (what's the difference?) I don't seem to have access to the objects created in the script after it completes.

For example, in my script I might have something like:

u = User.where('last_name = ?', 'Spock').first

If I start rails console and run that script using load or require, I see it working, I see the query happen, and I can 'put' attributes from the object inside the script and see them in the console output. But once the script is done, the variable u is undefined.

I'd like to run some code to set up a few objects and then explore them interactively. Can this be done? Am I doing something wrong or missing something obvious?

Dan Barron
  • 1,094
  • 2
  • 15
  • 30
  • 1
    `load` will include and execute the code from the file every time it is called, whereas `require` will only include it once and only once in an execution thread. – Jon Jan 27 '14 at 16:14

2 Answers2

11

Variables defined in your script will go out of scope once the file is loaded. If you want to use the variables in console, define them as instance variables or constants

@u = User.where('last_name = ?', 'Spock').first

or

USER = User.where('last_name = ?', 'Spock').first
usha
  • 28,973
  • 5
  • 72
  • 93
  • 1
    Also equivalent is: `User.find_by(last_name: 'Spock')` (also find the first record) but shorter – itsnikolay Jan 27 '14 at 16:06
  • Thanks to you both. Vimsha: I knew I was missing something obvious! This will save me a lot of time. itsnikolay: You learn something new every day! – Dan Barron Jan 27 '14 at 18:49
4

As explained in http://www.ruby-doc.org/core-2.1.2/Kernel.html#method-i-load:

In no circumstance will any local variables in the loaded file be propagated to the loading environment.

An option is to eval the file:

eval(File.read 'your_script.rb')

and the local variables will be there afterwards.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985