Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run a Ruby file in a Rails environment?

People also ask

How do I run a Rails application?

Go to your browser and open http://localhost:3000, you will see a basic Rails app running. You can also use the alias "s" to start the server: bin/rails s . The server can be run on a different port using the -p option. The default development environment can be changed using -e .

How do I open a Ruby file?

Open up IRB (which stands for Interactive Ruby). If you're using macOS open up Terminal and type irb , then hit enter. If you're using Linux, open up a shell and type irb and hit enter. If you're using Windows, open Interactive Ruby from the Ruby section of your Start Menu.


The simplest way is with rails runner because you don't need to modify your script.

http://guides.rubyonrails.org/command_line.html#rails-runner

Just say rails runner script.rb


Simply require environment.rb in your script. If your script is located in the script directory of your Rails app do

require File.expand_path('../../config/environment', __FILE__)

You can control the environment used (development/test/production) by setting the RAILS_ENV environment variable when running the script.

RAILS_ENV=production ruby script/test.rb

Runner runs Ruby code in the context of Rails non-interactively.

From rails runner command:

Usage: runner [options] ('Some.ruby(code)' or a filename)

    -e, --environment=name           Specifies the environment for the runner to operate under (test/development/production).
                                     Default: development

    -h, --help                       Show this help message.

You can also use runner as a shebang line for your scripts like this:

-------------------------------------------------------------
#!/usr/bin/env /Users/me/rails_project/script/rails runner

Product.all.each { |p| p.price *= 2 ; p.save! }
-------------------------------------------------------------

This is an old question, but in my opinion I often find it helpful to create a rake task... and it's actually very easy.

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

And then in the terminal run:

rake example:create_user

Locally this will be run in the context of your development database, and if run on Heroku it will be run while connected to your production database. I find this especially useful to assist with migrations, or modified tables.