6

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

 2 years ago
source link: https://blog.niclin.tw/2018/09/13/%E4%B8%8D%E8%A6%81%E5%9C%A8-rake-task-%E4%B8%AD%E5%AE%9A%E7%BE%A9-method-%E8%AB%8B%E7%94%A8-rakedsl/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Nic Lin's Blog

喜歡在地上滾的工程師

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK