模型显示重构多个区域设置消息rubocop

时间:2016-02-26 21:25:46

标签: ruby-on-rails routing refactoring ruby-style-guide

enter image description here

当我写这个方法时,我知道它可以写得更好,但它是一个MVP。现在,我正在努力了解专家们认为的方法以及如何解决警察问题。不断学习!

以下是有问题的控制器方法:

  def show
    if params[:id] && numeric?(params[:id])
      @job = Job.find_by(id: params[:id])
      if @job
        if @job.start_at
          if @job.end_at && @job.end_at >= Date.today
            @company = Company.find_by_id(@job.company_id)
            render 'jobs/show', layout: 'nested/job/show'
          else
            route_expired
          end
        else
          route_not_paid_for
        end
      else
        route_not_found_error
      end
    else
      route_not_found_error
    end
  end

反过来,这些会根据他们获得的错误类型调用一系列路线来指导用户去哪里:

  private

  def route_not_found_error
    flash[:error] = t('flash_messages.jobs.id.not_found')
    redirect_to new_job_url
  end

  def route_expired
    flash[:error] = t('flash_messages.jobs.id.expired')
    redirect_to new_job_url
  end

  def route_not_paid_for
    flash[:error] = t('flash_messages.jobs.id.not_paid_for')
    redirect_to job_payment_url(@job)
  end

对于专家们,您会如何处理?我知道这必须更清洁。

1 个答案:

答案 0 :(得分:2)

首先,我会将一些逻辑移到Job模型

def started?
  self.start_at.present?
end

def finished?
  self.end_at.present?
end

def expired?
  finished? && self.end_at < Date.today
end

接下来,在我看来,检查是否存在:id以及是否为数字是不必要的,您可以在控制器中使用rescue_from。把它们放在一起,你可以按如下方式重构节目

class JobsController < ApplicationController
  rescue_from ActiveRecord::RecordNotFound, with: :route_not_found_error

  def show
    @job = Job.find params[:id]

    route_not_paid_for unless @job.started?
    route_expired if @job.expired?

    @company = Compandy.find_by_id(@job.company_id)
    render 'jobs/show', layout: 'nested/job/show'
  end

  private

  ...

end