如何为我有点独立的 Ruby 脚本设置 Rails 环境? [英] How can I set the Rails environment for my somewhat stand alone Ruby script?

查看:32
本文介绍了如何为我有点独立的 Ruby 脚本设置 Rails 环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Rails 应用中有一个 Ruby 脚本,用于从 Twitter 加载一些数据.

I have a Ruby script in my Rails app that I use to load some data from Twitter.

将来我会将其设为自动后台进程,但现在我手动运行它,例如:

In the future I will make it an automatic background process, but for now I run it manually like:

ruby /lib/twitter/twitterLoad.rb

为了使用 Rails 模型类等,我将以下内容作为脚本的第一行:

In order to use the Rails model classes and such, I have the following as the top line of the script:

require "#{File.dirname(__FILE__)}/../../config/environment.rb"

默认使用开发环境.但是,我希望能够在某个时候选择生产环境.

By default, the development environment is used. But, I'd like to be able to choose the production environment at some point.

更新 #1:在 environment.rb 文件中设置 RAILS_ENV 常量.因此,我能够将 ENV['RAILS_ENV'] = 'production' 放在最顶部(在 environment.rb 之前)行并在某种程度上解决我的问题.所以,我的新问题是,可以通过命令行传入 env vars 吗?

Update #1: The RAILS_ENV constant is getting set in the environment.rb file. So, I was able to put ENV['RAILS_ENV'] = 'production' at the very top (before the environment.rb) line and solve my problem somewhat. So, my new question is, can do pass in env vars through the command line?

推荐答案

如果您要使用 rails 环境,最好的办法是将其设为 rake 脚本.为此,请将 twitter.rake 文件放入 lib/tasks 并像这样开始和结束:

If you're going to be using the rails environment, your best bet would be to make this a rake script. To do this, put a twitter.rake file into lib/tasks and begin and end it like this:

task(:twitter_load => :environment) do
  # your code goes here
end

那样的话,你就是通过遵循惯例"来做这件事,而且不会有那种难闻的气味".

That way, you're doing it by "following conventions" and it doesn't have that 'orrible smell associated with it.

这篇关于如何为我有点独立的 Ruby 脚本设置 Rails 环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆