如何优化此代码

时间:2016-08-11 05:09:32

标签: mysql ruby-on-rails query-optimization

我在帮助程序中使用此代码根据状态显示计数 -

    def to_do_count
        Task.where(status: 0).count
    end 

    def in_progress_count
        Task.where(status: 1).count
    end

    def paused_count
        Task.where(status: 2).count
    end

    def completed_count
        Task.where(status: 3).count
    end

我需要帮助来优化此代码,因为有很多重复。

4 个答案:

答案 0 :(得分:1)

    [self dismissViewControllerAnimated:NO completion:^{
            dispatch_async(dispatch_get_main_queue(), ^{ 
 [[NSNotificationCenter defaultCenter] postNotificationName:@"ShareArray" object:_selectedimgarray]; 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SharetitleArray" object:_newtile]; 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"sharevideooutputurl" object:_finalvideourl]; 
    [self.tabBarController setSelectedIndex:0];
        });
            }];

现在打电话:

def count_of(type)
    Task.where(status: get_status_type(type)).count
end 

def get_status_type(type)
   {to_do: 0, in_progress: 1, paused_count: 2, completed_count: 3}[type]
end

而不是

count_of(:to_do) 

答案 1 :(得分:1)

选项1

def task_count(status)
  Task
    .where(status: { to_do: 0, in_progress: 1, paused_count: 2, completed_count: 3 }[status])
    .count
end

task_count(:to_do) 
task_count(:in_progress)

选项2

您可以使用范围

来简化它
class Task
  scope :to_do,           -> { where(status: 0) }
  scope :in_progress,     -> { where(status: 1) }
  scope :paused_count,    -> { where(status: 2) }
  scope :completed_count, -> { where(status: 3) }
end

然后帮助器看起来像这样:

def task_count(status)
  Task.send(status).count
end

task_count(:to_do)

答案 2 :(得分:1)

使用哈希常量

TASK = {
  to_do: 0,
  in_progress: 1,
  paused_count: 2,
  completed_count: 3
}

def self.count_of(type)
  Task.where(status: TASK[type]).count
end

在课堂上调用

Task.count_of(:to_do)

答案 3 :(得分:1)

您可以定义STATUSES常量,然后使用Ruby中的运行时方法定义来定义这些方法。代码就像

STATUSES = {
  to_do:       0,
  in_progress: 1,
  paused:      2,
  completed:   3
}

def count_for(status)
  Task.where(status: status).count
end

STATUSES.each do |k, v|
  define_method("#{k}_count"){ count_for(v) }
end

现在你可以调用所有这些方法。因为它们是动态定义的

  • to_do_count
  • in_progress_count
  • paused_count
  • completed_count中
相关问题