0

这里有课,我需要收集一些关于喜欢、评论、内容、视图的统计信息

class UsersActivityTable

  def initialize(user_ids, content_ids, start_date, end_date)
    @user_ids, @content_ids, @start_date, @end_date = user_ids, content_ids,  start_date,  end_date
  end

  def rows
    @rows ||= @user_ids.map do |user_id|
                OpenStruct.new( :full_name => sum_users(user_id),
                                :contributed => sum_contributed(user_id),
                                :interacted => sum_interacted(user_id)
                              )
               end
  end

  private

  def sum_users(user_id)
    @sum_users ||= Hash[ User.value_of(:id, :first_name, :last_name).map{|usr| [usr[0], "#{usr[1]} #{usr[2]}"] } ]
    @sum_users[user_id]
  end

  def sum_contributed(user_id)
    @sum_contributed ||= Content.where(:user_id => @user_ids, :id => @content_ids)
                                .where('date(created_at) between ? and ? ', @start_date, @end_date)
                                .group(:user_id)
                                .count
    @sum_contributed[user_id].to_i
  end

  def sum_interacted(user_id)
    sum_comments(user_id).to_i + sum_views(user_id).to_i + sum_likes(user_id).to_i
  end

  def sum_comments(user_id)
    @sum_comments ||= Comment.where(:user_id => @user_ids, :content_id => @content_ids)
                             .where('date(created_at) between ? and ? ', @start_date, @end_date)
                             .group(:user_id)
                             .count
    @sum_comments[user_id]
  end

  def sum_likes(user_id)
    @sum_likes ||= Like.where(:user_id => @user_ids, :content_id => @content_ids)
                       .where('date(created_at) between ? and ? ', @start_date, @end_date)
                       .group(:user_id)
                       .count
    @sum_likes[user_id]
  end

  def sum_views(user_id)
    @sum_views ||= View.where(:viewable_type => 'Content', :user_id => @user_ids, :viewable_id => @content_ids)
                       .where('date(created_at) between ? and ? ', @start_date, @end_date)
                       .group(:user_id)
                       .count
    @sum_views[user_id]
  end
end

如您所见,有一些重复:

.where('date(created_at) between ? and ? ', @start_date, @end_date)
.group(:user_id)
.count

我为每个实体执行它。有什么方法可以应用条件 lambda 之类的吗?

我认为是可能的 - 在集合实例上定义方法并调用它:

# pseudo code
group_results = lambda{|el| el.where('date(created_at) between ? and ? ', @start_date, @end_date)
                             .group(:user_id)
                             .count }
Content.where(...).tap{|collection| collection.defune_method .... }.group_results
4

1 回答 1

1

有时对于非平凡的统计数据,返回您想要的所有内容的 find_by_sql 会更有效,甚至可能比复杂的 ruby​​ 更清晰。

当然是 YMMV :)

于 2012-10-01T13:51:52.790 回答