Run script in Rails console and have access to objects created?

rails-console, ruby-on-rails, ruby-on-rails-4

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

Problem

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?

Original source