Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top