当有类似的模型时,如何简化我的助手并使其更干燥?

发布于 2024-09-08 23:16:28 字数 399 浏览 2 评论 0原文

我开始遇到一些困难,使其更加干燥:

http://gist.github.com/471225

它的要点是:

我有一堆模型,contact_email、contact_call、contact_letter 等等。

它们本质上是我实例化与特定联系人实例/记录相匹配的电子邮件模型实例(将其视为模板)的一种方法。

因为它们引用的模型不同,所以我需要一种方法让控制器引用正确的模型。

但这正变得越来越复杂。我尝试了使用“发送”和 Ruby 部分的不同方式来识别关联的类,因此我不需要明确声明它,但运气不佳。

因此——非常不干……救命!

I am starting to have some difficulty making this more DRY:

http://gist.github.com/471225

The gist of it is this:

I have a bunch of Models, contact_email, contact_call, contact_letter, etcetera.

They essential were a way for me to instantiate instances of the Email model (think of it as a template) matched with a specific instance/record of Contact.

Because the Models they reference were different, I needed a way to have the controller reference the right Model.

But this is getting complicated. I played with different ways of using 'send' and parts of Ruby to identify the associated Class so I don't need to explicitly state it, but not having luck.

Thus -- very undry...help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦太阳 2024-09-15 23:16:28

好吧,这是我的第一次攻击:

def show_contact_status(contact, method, contact_class)
  if @contact_method = contact_class.for_contact(contact, method).first
    @contact_method.formatted_status_message
  else
    "no status"
  end
end

然后在您的模型中,您将添加一个命名范围:

named_scope :for_contact, lambda {|contact, method| 
  {:conditions => {:contact_id => contact.id, :email_id => method.id}}
}

然后在您的 ContactEmail 模型中添加一个 formatted_status_message 方法:

def formatted_status_message
  "#{self.status.to_s} (#{self.date_sent.to_s(:long)}"
end

在您的其他模型中:

def formatted_status_message
  "sent #{self.date_sent_to_s(:long)}"
end

您将调用电子邮件的方法:

show_contact_status(contact, method, ContactEmail)

我尝试尽可能多地移动到模型层并利用它,而不是在本例中进行元编程。

well, here is my first whack at it:

def show_contact_status(contact, method, contact_class)
  if @contact_method = contact_class.for_contact(contact, method).first
    @contact_method.formatted_status_message
  else
    "no status"
  end
end

And then in your models, you would add a named scope:

named_scope :for_contact, lambda {|contact, method| 
  {:conditions => {:contact_id => contact.id, :email_id => method.id}}
}

and then a formatted_status_message method in your ContactEmail model:

def formatted_status_message
  "#{self.status.to_s} (#{self.date_sent.to_s(:long)}"
end

And in your other models:

def formatted_status_message
  "sent #{self.date_sent_to_s(:long)}"
end

and you would call the method for email:

show_contact_status(contact, method, ContactEmail)

I tried to move as much as possible to the model layer and leverage that, instead of metaprogramming in this case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文