Pass ruby script file to rails console

Solution 1:

Actually, the simplest way is to run it with load inside the rails console

 load './path/to/foo.rb'

Solution 2:

You can use

bundle exec rails runner "eval(File.read 'your_script.rb')"

UPDATE:

What we also have been using a lot lately is to load the rails environment from within the script itself. Consider doit.rb:

#!/usr/bin/env ruby

require "/path/to/rails_app/config/environment"

# ... do your stuff

This also works if the script or the current working directory are not within the rails app's directory.

Solution 3:

In the meantime, this solution has been supported.

rails r PATH_TO_RUBY_FILE

Much simpler now.

Solution 4:

script/console --irb=pry < test.rb > test.log

simple, dirty, and block the process at the end, but it does the job exactly like I wanted.

Solution 5:

Consider creating a rake task.

For code that I need to create records or support migrations, for example, I often create a rake task like that from this answer. For example:

In lib/tasks/example.rake:

namespace :example do
  desc "Sample description you'd see if you ran: 'rake --tasks' in the terminal"
  task create_user: :environment do
    User.create! first_name: "Foo", last_name: "Bar"
  end
end

And then in the terminal run:

rake example:create_user