How can I run a ruby class from rake file?

ぃ、小莉子 提交于 2019-12-07 11:14:07

问题


I want to run a ruby class from a sample.rake file.

Consider myruby.rb is a ruby file.

I want to run this from sample.rake like ruby myruby.rb


回答1:


Adding to what @tobias has to say here you go with an example script

sample content of myruby.rb

puts "hello world"

Create file called Rakefile

task :default => [:test]

task :test do
    ruby "my_file.rb"
end

Now if you invoke rake it should file up hello world text in console.

Update

It would make more sense if you wrap your call in a function call as suggested already by @tobias

So your Rakefile would become something like

require './myruby.rb'
task :default => [:test]

task :test do
  ruby "my_file.rb"
end

task :test2 do
  do_something
end

and myruby.rb

def do_something
  puts "do something"
end

Now rake test2 should spit out do something




回答2:


You could use system calls

e.g. http://www.ruby-doc.org/core-2.0/Kernel.html#method-i-system

Alternatively assuming your reason for doing it this way is that myruby.rb is a plain ruby script that just works on execution:

You could think about enclosing the content of the script into a method, require 'myruby' in the rake task and executing said method in the rake task.



来源:https://stackoverflow.com/questions/18209388/how-can-i-run-a-ruby-class-from-rake-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!