在 Rails 中,我如何委托给类方法 [英] In rails how can I delegate to a class method

查看:21
本文介绍了在 Rails 中,我如何委托给类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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...

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...

有什么想法吗?我什至可以委托给这样的类方法吗?我可能有另外一个或两个以这种方式扩展 Task 的类,所以我很好奇这是如何以一种不会向每个实现类复制一堆代码的方式工作的.

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.

推荐答案

你正在拿起 ActiveSupport 委托核心扩展.delegate 助手为当前类定义了一个 instance 方法,以便它的实例将调用委托给那个实例上的某个变量.

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

但这假设 Important.task 是对 Task 类的引用(它不是)

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

这篇关于在 Rails 中,我如何委托给类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆