Back

Rails console run code from file

added on :: 21 October 2014

Say you don't like to type in Rails console or Ruby's IRB(Interactive Ruby Shell) and rather user your text editor to write commands and run that file.

With Rails open up an rails console session

Then create a file in the public folder in your application. Better that to be a hard to guess file name (SecureRandom.uuid).  Or the tmp directory  or where ever that is not on Rails's load path.

2855f6d7-cfda-4afd-950b-d502d4779a7b.rb


Write the command on to that file ie.

User.last.first_name

then to see that command run in console

load Dir.pwd + "/public/2855f6d7-cfda-4afd-950b-d508d4779a7b.rb"


What this does is. With Dir.pwd goes to the Rails project directort( pwd is a UNIX command to see where you are on any given time -current working direcory- http://en.wikipedia.org/wiki/Pwd)

This way, you can write all your code on to this file (the playground file) and and press the  "up arrow" plus enter to run the last command in shell

Rather than typing that file execution command all the time you could have this line on top of the file commented out # load Dir.pwd + "/public/2855f6d7-cfda-4afd-950b-d508d4779a7b.rb" and copy pasts at your leisure.

The same command can be used in a Ruby project as well. It would load that file in an IRB session.

Also you can run a ruby file on command line without a IRB console session by

> ruby hello.rb


Back