Ruby / Rails 元编程:动态生成辅助方法
我正在尝试为给定的模型名称数组动态生成一些计数方法,然后可以在视图/帮助器中使用这些方法:
# create dynamic count methods for each model we want
['model', 'other_model', 'next_model'].each do |name|
class_eval{
"def total_#{name.underscore}s_count
total_#{name.underscore}s_count ||= #{name.camelcase}.all.count
end"
}
end
但是,我有几个问题:
- 如果我希望能够调用这些方法,则该代码应该放在哪里在一个视图中?
- 这些方法将添加到什么类中?例如,我将如何调用它们,因为我不确定它们是否属于 User 等类,因为它们适用于一堆模型。
- 有更好的方法吗?
I am trying to generate some count methods dynamically for a given array of model names that I can then use in a view/helper:
# create dynamic count methods for each model we want
['model', 'other_model', 'next_model'].each do |name|
class_eval{
"def total_#{name.underscore}s_count
total_#{name.underscore}s_count ||= #{name.camelcase}.all.count
end"
}
end
However, I have a few questions:
- Where should this code go if I want to be able to call these methods in a view?
- What class would these methods be added to? For instance, how would I go about calling them since I'm not sure if they belong to the User, etc. class since they are for a bunch of models.
- Is there a better way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用 mixin 并将其包含在相关的模型类中。 http://juixe.com/techknow/index.html php/2006/06/15/mixins-in-ruby/
这些方法将在您的视图中的模型实例上可用。
You should use a mixin and include it in the relevant model classes. http://juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/
The methods will be available on the model instances in your views.
您试图解决的问题(防止您的视图命中模型方法)并不是通过将相同的逻辑委托给视图助手来解决的。如果您想遵守 MVC 约定以防止视图触发 SQL 查询,则应该在控制器中执行此操作。
然后,您就可以得到每个传递的模型的计数的良好哈希值:
The problem you're trying to solve (keeping your views from hitting model methods) isn't solved by delegating the same logic to a view helper. You should be doing this in your controllers if you want to stick to the MVC convention of keeping your views from triggering SQL queries.
You then have a nice hash of the counts of each of the models passed: