开发者

Best way to DRY that and clarify code better

开发者 https://www.devze.com 2023-02-25 04:10 出处:网络
i\'m searching for the better way on keeping my controllers clean and readable. Take a look at this controller action :

i'm searching for the better way on keeping my controllers clean and readable. Take a look at this controller action :

  def start
    @work_hours = params[:work_hours].to_i

    redirect_to labor_url, :flash => {:error => I18n.t('error.invalid_post')} and return unless (1..8).include? @work_hours
    redirect_to labor_url, :flash => {:error => I开发者_JAVA百科18n.t('error.working')} and return if current_user.working?
    redirect_to labor_url, :flash => {:error => I18n.t('error.has_quest')} and return if current_user.has_tavern_quest?

    redirect_to labor_path 
  end

As you can see, these are doing the same thing if a condition happens. They are setting a flash message and redirecting to a url(and returning). While this seems ok to me in terms of clarification, i can't help but notice a bit of repetition in the redirects and i don't like setting flash[:error] with a translation in such an ugly manner.

Do you think this can be done in a better, DRYer and more readable way ?


the url is the same for all redirects (if i see correctly, no difference between url and path), so i would refactor that as follows:

def start
  @work_hours = params[:work_hours].to_i

  flash[:error] = I18n.t('error.invalid_post') unless (1..8).include? @work_hours
  flash[:error] = I18n.t('error.working') if current_user.working?
  flash[:error] = I18n.t('error.has_quest') if current_user.has_tavern_quest?

  redirect_to labor_path 
end

So: set the flash if needed, and redirect to labor_path in all cases. Does that help?

If in case of error you would need to redirect to something else, do something like:

def start
  @work_hours = params[:work_hours].to_i

  flash[:error] = I18n.t('error.invalid_post') unless (1..8).include? @work_hours
  flash[:error] = I18n.t('error.working') if current_user.working?
  flash[:error] = I18n.t('error.has_quest') if current_user.has_tavern_quest?

  redirect_to labor_error_path and return if flash[:error]
  redirect_to labor_path 
end

If conditions are not mutually exclusive, i would write it like this:

def start
  @work_hours = params[:work_hours].to_i

  flash[:error] = unless (1..8).include? @work_hours 
    I18n.t('error.invalid_post') 
  elsif current_user.working?
    I18n.t('error.working')
  elsif current_user.has_tavern_quest?
    I18n.t('error.has_quest') 
  else
    nil
  end

  redirect_to labor_error_path and return if flash[:error]
  redirect_to labor_path 
end

I am not entirely sure if the else nil is explicitly needed. Does this help?

0

精彩评论

暂无评论...
验证码 换一张
取 消