【问题标题】:Ruby / Rails metaprogramming: generating helper methods on the flyRuby / Rails 元编程:动态生成辅助方法
【发布时间】:2011-06-08 13:43:50
【问题描述】:

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

  # 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. 有更好的方法吗?

【问题讨论】:

  • total_model_count 比 Model.count 有什么优势?
  • 将直接模型调用排除在我的视图之外

标签: ruby-on-rails ruby ruby-on-rails-3 metaprogramming dynamically-generated


【解决方案1】:

您应该使用 mixin 并将其包含在相关的模型类中。 http://juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/

这些方法将在您的视图中的模型实例上可用。

【讨论】:

    【解决方案2】:

    将相同的逻辑委托给视图助手并不能解决您试图解决的问题(防止视图命中模型方法)。如果您想遵守 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 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2013-08-14
      • 2020-03-01
      • 2012-12-30
      相关资源
      最近更新 更多