开发者

Running an external .rb file from within a rails 3 controller?

开发者 https://www.devze.com 2023-02-03 07:17 出处:网络
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

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:

  1. One that encapsulates the script's functionality in classes and/or modules.
  2. 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.

  1. Background jobs: http://codeforpeople.rubyforge.org/svn/bj/trunk/README
  2. Or delayed_job: https://github.com/tobi/delayed_job
  3. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消