简体   繁体   中英

Calling a ruby script from Rails with different gemfile

I have a ruby script I wrote which generates data and loads it to MongoDB. I am now trying to call this load script from seed.rb of my Rails app (so I can run via rake db:seed)

I attempted to call it from rails using this code:

system( "ruby data_load/db_load.rb -a data_load/doc1.json" )

When that code executes, I get the following error. (Note it runs fine from the command line):

data_load/db_load.rb:15:in `require': cannot load such file -- mongo (LoadError)
from data_load/db_load.rb:15:in `<main>'

The top of db_load.rb looks like this:

# includes gems from gemfile
require 'rubygems'
require 'bundler/setup'
Bundler.setup
require 'mongo'
require_relative 'load_scripts/cmd_options'
require_relative 'load_scripts/build_index'
....
include Mongo

The script has it's own gemfile in the data_load directory.

My guess is ruby is running the script using the bundle for the rails application instead of the shell script.

Any suggestions on how I can execute this script?

I believe the problem is where Bundler is looking for the Gemfile. Since your script is being run in the parent directly it is finding the Gemfile for the main app.

Set the BUNDLE_GEMFILE before calling your script:

system "BUNDLE_GEMFILE=data_load/Gemfile ruby data_load/db_load.rb -a data_load/doc1.json"

I'm sorry but I think you can't do it, unless you run the script as a different process (like a shell command), doing it is easy:

`shell_command params`

Just use the correct path and params.

Otherwise, consider that a gemfile is "more or less" at its basic level, a bunch of require (or load) statements, so loading a different gemfile would overwrite the original one, creating a lot of issue with rails after that.

The subprocess command is a good idea, however you can only pass string as params, not in-memory objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM