Run Rails commands outside of console

Ruby on-RailsRubyRuby on-Rails-3Console

Ruby on-Rails Problem Overview


With my large application, the Rails console takes a while to load up. Is there a way to single commands more easily?

I'd also like to be able to automate stuff, and echo "query" | rails console isn't a great way to do things.

Thoughts?

EDIT: What about a long-running process that I can ping queries to whenever I have need?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

There are two main ways to run commands outside console:

  1. Rake task which depends on :environment

  2. rails runner (previously script/runner), eg:

    $ rails runner "query"
    

Both are pretty well documented on the rails guide: https://guides.rubyonrails.org/command_line.html#bin-rails-runner

btw: both of these methods will still take the same time as a console to fire up, but they are useful for non-interative tasks.

Solution 2 - Ruby on-Rails

Just pipe it in:

echo 'puts Article.count' | bundle exec rails c

It should now be a lot faster than when then the question was originally asked, because of Spring. It's not immediate, but still a lot faster than spinning up the whole app. Use this for the fast lane, it should run in under a second (assuming your required command is fast):

echo 'puts Article.count' | spring rails c

If you really want a single long-running process, you could easily do it by creating a controller action that simply runs whatever you POST to it, then send commands to it using curl behind an alias. The action would of course be completely insecure and should be triple-guarded against running anywhere near production, but it would be easy to setup.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontekknolagiView Question on Stackoverflow
Solution 1 - Ruby on-RailsTim PetersView Answer on Stackoverflow
Solution 2 - Ruby on-RailsmahemoffView Answer on Stackoverflow