开发者

Ruby / Rails metaprogramming: generating helper methods on the fly

I am trying to generate some count 开发者_Python百科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?


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.


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 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜