I have a rails 3 controller and a very simple ruby (.rb) file in my server index directory. I would like to run the file from within my controller- what is the best way 开发者_开发知识库to do this?
You could try load
: http://www.ruby-doc.org/core/classes/Kernel.html#M001417
Here's one example
# in your controller
def create
load('/path/to/your/file.rb')
end
However, I would say it's bad practice in general to call Ruby code from Rails by running an outside script. I think you'd be better breaking your Ruby file into two:
- One that encapsulates the script's functionality in classes and/or modules.
- One that invokes said classes/modules from the command line.
Then, in your Rails app, just require
#1 and use the classes/modules.
For example, suppose your script is currently called simple.rb and looks like this:
# simple.rb
puts 'Hello, world!'
You would then create hello_world.rb
and do this:
# hello_world.rb
class HelloWorld
def say_it
puts 'Hello, world!'
end
end
You would replace the contents of simple.rb
with this:
require 'hello_world.rb'
HelloWorld.new.say_it
Then, in your controller, you could bypass simple.rb
and just use the HelloWorld
class directly:
Do you want the script to run in it's own process? If so, check these out.
- Background jobs: http://codeforpeople.rubyforge.org/svn/bj/trunk/README
- Or delayed_job: https://github.com/tobi/delayed_job
Also, you can use script runner like this:
system " RAILS_ENV=#{RAILS_ENV} ruby #{RAILS_ROOT}/script/runner 'MyModel.my_method(some_param)' & "
The & at the end will put the task into another process.
精彩评论