模型显示重构多个语言环境消息 rubocop
model show refactor multiple locale messages rubocop
当我写这个方法时,我知道它可以写得更好,但它是一个 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
对于专家,您将如何处理这个问题?我知道这一定更干净。
首先,我会将一些逻辑移动到 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
当我写这个方法时,我知道它可以写得更好,但它是一个 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
对于专家,您将如何处理这个问题?我知道这一定更干净。
首先,我会将一些逻辑移动到 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