`

一个rails代码优化例子

阅读更多
查询是mongo mapper的
    def search_followers options, index
      options = inner_option_convert options
      follow_list = options[:searchterm].blank? ? index.followers_and_dates : index.followers_and_dates.find_all{|follow| follow[:follower].email =~ /.*#{options[:searchterm]}.*/} 
      follow_list = follow_list.sort_by{|follow| follow[:follower].email} if options[:sort_by] == 'name'
      follow_list = follow_list.sort_by{|follow| follow[:date]} if options[:sort_by] == 'date'
      follow_list.collect{|follow| follow[:follower]}.paginate( options )
    end
    
    def search_alerts options, index
      options = inner_option_convert options
      alert_list = index.alerts
      alert_list = alert_list.sort_by{|alert| alert.created_at} if options[:sort_by] == 'date' 
      alert_list = alert_list.sort_by{|alert| alert.alert_rule._type } if options[:sort_by] == 'type'
      alert_list = alert_list.collect{|alert| alert if alert.category == options[:filter]}.compact unless options[:filter] == 'all'
      alert_list.paginate( options )        
    end



之后变成


    def search_followers options, index
      options = inner_option_convert options
    if options[:sort_by] == 'date'
      u_ids = User.all( :conditions => {:email => /.*#{options[:searchterm]}.*/i }).map(&:id)
      following = Following.all( :conditions => { :index_id => index.id, :follower_id.in =>  u_ids }, :order => "created_at desc")
      f_ids = following.map(&:follower_id)
      user_hash = User.find(f_ids).group_by(&:id)
      f_ids.collect{|id| user_hash[id][0]}.paginate( options )
    else
      f_ids = Following.all( :conditions => { "index_id" => index.id }).map(&:follower_id)
      User.all( :conditions => {:email => /.*#{options[:searchterm]}.*/i, :id.in => f_ids }, :order => 'email asc').paginate( options )
    end  
    end
    
    def search_alerts options, index
      options = inner_option_convert options
      sort_by = case options[:sort_by]
              when 'type' : 'category asc'
              else 'created_at desc'
              end
      condition= { "index_id" => index.id } 
      condition["category"] = options[:filter] unless options[:filter].blank? or options[:filter] == 'all'
      alert_list = Alert::Alert.all( :conditions => condition, :order=> sort_by )
      alert_list.paginate( options )        
    end
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics