How do I run Rake tasks within a Ruby script?

前端 未结 4 1282
抹茶落季
抹茶落季 2020-12-01 00:14

I have a Rakefile with a Rake task that I would normally call from the command line:

rake blog:post Title

I\'d like to write a

4条回答
  •  情话喂你
    2020-12-01 00:38

    You can use invoke and reenable to execute the task a second time.

    Your example call rake blog:post Title seems to have a parameter. This parameter can be used as a parameter in invoke:

    Example:

    require 'rake'
    task 'mytask', :title do |tsk, args|
      p "called #{tsk} (#{args[:title]})"
    end
    
    
    
    Rake.application['mytask'].invoke('one')
    Rake.application['mytask'].reenable
    Rake.application['mytask'].invoke('two')
    

    Please replace mytask with blog:post and instead the task definition you can require your rakefile.

    This solution will write the result to stdout - but you did not mention, that you want to suppress output.


    Interesting experiment:

    You can call the reenable also inside the task definition. This allows a task to reenable himself.

    Example:

    require 'rake'
    task 'mytask', :title do |tsk, args|
      p "called #{tsk} (#{args[:title]})"
      tsk.reenable  #<-- HERE
    end
    
    Rake.application['mytask'].invoke('one')
    Rake.application['mytask'].invoke('two')
    

    The result (tested with rake 10.4.2):

    "called mytask (one)"
    "called mytask (two)"
    

提交回复
热议问题