How can I run a ruby class from rake file?

Prince picture Prince · Aug 13, 2013 · Viewed 7.9k times · Source

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

Answer

ch4nd4n picture ch4nd4n · Aug 13, 2013

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