问题
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.
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
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
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.
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).
回答1:
my preferred way of handling this sort of thing is as follows:
- wrap each script in its entirety in a module with one action method
- place the file which contains the method-wrapped script within lib/ (you can put multiple method-scripts in one file, or keep them one-per-file
- require everything within lib in your Rakefile
- within the rake task, include the module and call the method
so, in very simple terms:
# lib/foo.rb
module Foo
def bar
puts "called me"
end
end
and:
# 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
回答2:
I think your problem stems from not requiring the proper path to your lib scripts. Instead of doing require 'lib/another_script.rb'
from your script (which lives in lib), do something like require File.expand_path(File.dirname(__FILE__)) + '/another_script'
. Expanding the path will give you the full path to the script, so ruby shouldn't have any problem loading the file.
来源:https://stackoverflow.com/questions/9304121/how-to-integrate-previously-external-ruby-scripts-into-a-rails-app-and-call-them