Nic Lin's Blog

喜歡在地上打滾的 Rails Developer

不要在 rake task 中定義 method, 請用 RAKE::DSL

rake task 的 scope 是全域的,如果在任意的 rake 檔案中定義了 method,表面上看起來只有執行到該 task 時會用,但其實是等於為 main:Object 整個 class 定義了 private method,一次性污染了全部的 code。

為了避免污染,可以用 service 對 task 進行封裝,不過更佳的解法可以用 Rake::DSL

DSL is a module that provides task, desc, namespace, etc. Use this when you’d like to use rake outside the top level scope.

範例:

# lib/tasks/bicycle.rake

class BicycleTasks
  include Rake::DSL

  def initialize
    namespace :bicycle do
      task :assemble do
        bicycle = Bicycle.new

        # Assemble the bicycle:
        attach_wheels(bicycle)
        attach_handlebars(bicycle)
        attach_brakes(bicycle)
      end
    end
  end

  private

  def attach_wheels(bicycle)
    # ...
  end

  def attach_handlebars(bicycle)
    # ...
  end

  def attach_brakes(bicycle)
    # ...
  end
end

# Instantiate the class to define the tasks:
BicycleTasks.new

參考來源

Share Comments
comments powered by Disqus