簡體   English   中英

在rails中,我如何委托給一個類方法

[英]In rails how can I delegate to a class method

class Task < ActiveRecord::Base
  attr_accessible :due_date, :text

  def self.this_week
    where(:due_date => Date.today.beginning_of_week..Date.today.end_of_week)
  end
end

class Important < ActiveRecord::Base
  attr_accessible :email

  has_one :task, :as => :taskable, :dependent => :destroy

  delegate this_week, :to => :task
end

到目前為止,當我嘗試Important.this_week時,這個代表沒有按預期工作。 我得到一個錯誤,說沒有為類定義this_week方法...

有任何想法嗎? 我甚至可以委托給像這樣的類方法嗎? 我可能會以這種方式使用另一個或兩個擴展Task ,所以我很好奇這是如何以不會將一堆代碼復制到每個實現類的方式工作的。

您正在獲取ActiveSupport委派核心擴展 delegate助手,這樣它的實例委托給該實例上某個變量調用定義當前類的實例方法。

如果要在類級別委派,則需要打開單例類並在那里設置委派:

class Important < ActiveRecord::Base
  attr_accessible :email

  has_one :task, :as => :taskable, :dependent => :destroy

  class << self
    delegate :this_week, :to => :task
  end
end

但是這假設Important.task是對Task類的引用(它不是)

我沒有依賴代表團幫助,這將使你的生活變得困難,我建議在這里明確代理:

class Important < ActiveRecord::Base
  attr_accessible :email

  has_one :task, :as => :taskable, :dependent => :destroy

  class << self
    def this_week(*args, &block)
      Task.this_week(*args, &block)
    end
  end
end

考慮繼承,將方法委托給類方法:

delegate :this_week, :to => :class

你可以委托給一個特定的類(參見Isaac Betesh的回答):

delegate :this_week, :to => :Task

文檔可在此處獲取: http//api.rubyonrails.org/classes/Module.html#method-i-delegate

您可以將方法委托給常量 - 它只是區分大小寫。 此外,必須將方法的名稱作為符號傳遞給delegate

class Important < ActiveRecord::Base
  delegate :this_week, :to => :Task
  # Note ':this_week' instead of 'this_week'
  # Note 'Task' instead of 'task'
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM