如何将以前的外部 ruby​​ 脚本集成到 Rails 应用程序中并从 rake 任务中调用它们? [英] How to integrate previously external ruby scripts into a Rails app and call them from a rake task?

查看:29
本文介绍了如何将以前的外部 ruby​​ 脚本集成到 Rails 应用程序中并从 rake 任务中调用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 3.1.x 应用程序之外编写了一些额外的脚本,但是现在是直接从 Rails 应用程序的数据库中提取数据而不是使用某些数据导出的时候了.

I have some additional scripts that I've written outside of my Rails 3.1.x app, however the time has come to pull data from the database of the Rails app directly rather than utilizing some exports of the data.

为此,我想将脚本集成到我的 rails 应用程序中.迄今为止,我已经基于模型中的方法运行 rake 任务,例如在我的 lib/taks/app.rake 中:

To this end, I'd like to integrate the scripts into my rails app. Hitherto I've run rake tasks based on methods in the models such as having this in my lib/taks/app.rake:

desc "Does something."
task :do_some_things => :environment do
  ModelName.some_method
  ModelName.another_method
end

如果我将我的脚本基本上放在 lib 中,我是否能够从 rake 任务中调用这些脚本?或者我是否需要模型中的调用方法require lib/my_script.rb?

If I were to place my scripts essentially into lib, would I be able to call these from a rake task? Or would I need a calling method in the model that would require lib/my_script.rb?

我曾尝试编写这样的任务:

I have attempted to write a task like this:

task :run_me => :environment do
  `bundle exec lib/script.rb`
end

然后当它执行并且我在那个 script.rb (require 'lib/another_script.rb') 中有一个 require 我最终得到无法加载这样的文件" 错误.

Then when this executes and I have a require within that script.rb (require 'lib/another_script.rb') I end up getting "cannot load such file" errors.

我目前显然是在以错误的方式处理这个问题.

I'm obviously approaching this the wrong way at present.

似乎我应该在 rake 任务中简单地调用一个方法,然后调用/lib 或其他地方(最合适的地方)下的支持脚本.

It seems as though I should simply have a method invocation in the rake task that would then call the supporting scripts under /lib or elsewhere (wherever would be most appropriate).

推荐答案

我处理这类事情的首选方式如下:

my preferred way of handling this sort of thing is as follows:

  • 使用一个操作方法将每个脚本整体包装在一个模块中
  • 将包含方法包装脚本的文件放在 lib/中(您可以将多个方法脚本放在一个文件中,也可以一个文件保存一个)
  • 需要 Rakefile 中 lib 中的所有内容
  • 在 rake 任务中,包含模块并调用方法

所以,简单来说:

# lib/foo.rb
module Foo
  def bar
    puts "called me"
  end
end

和:

# Rakefile
require File.expand_path('../config/application', __FILE__)
Dir[
  File.expand_path(Rails.root.join 'lib', '**', '*.rb')
].each {|f| require f}

desc "does bar from lib"
task :do_bar do
  include Foo
  bar
end

这篇关于如何将以前的外部 ruby​​ 脚本集成到 Rails 应用程序中并从 rake 任务中调用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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