In rails how can I delegate to a class method

后端 未结 3 671
半阙折子戏
半阙折子戏 2020-12-29 21:25
class Task < ActiveRecord::Base
  attr_accessible :due_date, :text

  def self.this_week
    where(:due_date => Date.tod         


        
相关标签:
3条回答
  • 2020-12-29 21:42

    You can delegate a method to a constant--it's just case sensitive. Also, the name of the method must be passed to delegate as a Symbol.

    class Important < ActiveRecord::Base
      delegate :this_week, :to => :Task
      # Note ':this_week' instead of 'this_week'
      # Note 'Task' instead of 'task'
    end
    
    0 讨论(0)
  • 2020-12-29 21:47

    Delegate a method to a class method, considering inheritance:

    delegate :this_week, :to => :class
    

    You can delegate to a specific class like so (see also Isaac Betesh's answer):

    delegate :this_week, :to => :Task
    

    Docs are available here: http://api.rubyonrails.org/classes/Module.html#method-i-delegate

    0 讨论(0)
  • 2020-12-29 21:55

    You're picking up the ActiveSupport delegation core extension. The delegate helper defines an instance method for the current class so that instances of it delegate calls to some variable on that instance.

    If you want to delegate at the class level, you need to open up the singleton class and set up the delegation there:

    class Important < ActiveRecord::Base
      attr_accessible :email
    
      has_one :task, :as => :taskable, :dependent => :destroy
    
      class << self
        delegate :this_week, :to => :task
      end
    end
    

    But this assumes that Important.task is a reference to the Task class (which it is not)

    Rather than relying on the delegation helper, which is just going to make your life difficult, I'd suggest explicit proxying here:

    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
    
    0 讨论(0)
提交回复
热议问题