Ruby / Rails 元编程:动态生成辅助方法

发布于 2024-11-14 14:40:51 字数 529 浏览 2 评论 0原文

我正在尝试为给定的模型名称数组动态生成一些计数方法,然后可以在视图/帮助器中使用这些方法:

  # 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

但是,我有几个问题:

  1. 如果我希望能够调用这些方法,则该代码应该放在哪里在一个视图中?
  2. 这些方法将添加到什么类中?例如,我将如何调用它们,因为我不确定它们是否属于 User 等类,因为它们适用于一堆模型。
  3. 有更好的方法吗?

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:

  1. Where should this code go if I want to be able to call these methods in a view?
  2. 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.
  3. Is there a better way of doing this?

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

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

发布评论

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

评论(2

只为一人 2024-11-21 14:40:51

您应该使用 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.

葮薆情 2024-11-21 14:40:51

您试图解决的问题(防止您的视图命中模型方法)并不是通过将相同的逻辑委托给视图助手来解决的。如果您想遵守 MVC 约定以防止视图触发 SQL 查询,则应该在控制器中执行此操作。

def index
  models = Foo, Bar, Bat
  @counts = models.inject({}) do |result, model|
    result[model.name.downcase.to_sym] = model.count
    result
  end
end

然后,您就可以得到每个传递的模型的计数的良好哈希值:

@counts #=> { :foo => 3, :bar => 59, :bat => 42 }

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.

def index
  models = Foo, Bar, Bat
  @counts = models.inject({}) do |result, model|
    result[model.name.downcase.to_sym] = model.count
    result
  end
end

You then have a nice hash of the counts of each of the models passed:

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