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

I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I'd like to just give it the file name and arguments. I'm pretty sure this is possible since I've done it before. Can someone remind me how to do this?

75655 次浏览

只需要在你的脚本 environment.rb。如果你的脚本位于你的 Rails 应用程序的 script目录做

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

最简单的方法是使用 rails runner,因为不需要修改脚本。

runner在 Rails 上下文中非交互地运行 Ruby 代码。

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

就说 rails runner script.rb

Runner 在 Rails 上下文中非交互地运行 Ruby 代码。

rails runner命令:

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! }
-------------------------------------------------------------

这是一个古老的问题,但在我看来,我经常发现创建一个 rake 任务是有帮助的... ... 而且它实际上非常简单。

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.

你只需要:

bundle exec rails r ~/my_script.rb