문제

나는 Rakefile 일반적으로 명령줄에서 호출하는 Rake 작업을 사용합니다.

rake blog:post Title

Rake 작업을 여러 번 호출하는 Ruby 스크립트를 작성하고 싶지만 내가 볼 수 있는 유일한 해결책은 ``(백틱) 또는 system.

이를 수행하는 올바른 방법은 무엇입니까?

도움이 되었습니까?

해결책

~에서 timocracy.com:

require 'rake'
require 'rake/rdoctask'
require 'rake/testtask'
require 'tasks/rails'

def capture_stdout
  s = StringIO.new
  oldstdout = $stdout
  $stdout = s
  yield
  s.string
ensure
  $stdout = oldstdout
end

Rake.application.rake_require '../../lib/tasks/metric_fetcher'
results = capture_stdout {Rake.application['metric_fetcher'].invoke}

다른 팁

이는 Rake 버전 10.0.3에서 작동합니다.

require 'rake'
app = Rake.application
app.init
# do this as many times as needed
app.add_import 'some/other/file.rake'
# this loads the Rakefile and other imports
app.load_rakefile

app['sometask'].invoke

knut이 말했듯이 reenable 여러 번 호출하려는 경우.

당신이 사용할 수있는 invoke 그리고 reenable 작업을 두 번째로 실행합니다.

귀하의 예시 통화 rake blog:post Title 매개변수가 있는 것 같습니다.이 매개변수는 다음에서 매개변수로 사용될 수 있습니다. invoke:

예:

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')

교체해주세요 mytask ~와 함께 blog:post 대신에 작업 정의를 사용할 수 있습니다. require 당신의 레이크 파일.

이 솔루션은 결과를 stdout에 기록하지만 출력을 억제한다고 언급하지 않았습니다.


흥미로운 실험:

전화를 걸 수 있습니다. reenable 작업 정의 내부에도 있습니다.이를 통해 작업이 스스로 다시 활성화될 수 있습니다.

예:

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')

결과(rake 10.4.2로 테스트):

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

Rails가 로드된 스크립트에서(예: rails runner script.rb)

def rake(*tasks)
  tasks.each do |task|
    Rake.application[task].tap(&:invoke).tap(&:reenable)
  end
end

rake('db:migrate', 'cache:clear', 'cache:warmup')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top