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
So far this delegate is not working as expected, when I try Important.this_week. I get an error saying there is no method this_week defined for class…
Any ideas? Can I even delegate to a class method like this? I may have another class or two extending Task in this way, so I’m curious how this works in a way that doesn’t duplicate a bunch of code to each implementing class.
You’re picking up the ActiveSupport delegation core extension. The
delegatehelper 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:
But this assumes that
Important.taskis a reference to theTaskclass (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: