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 => I18n.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:
So: set the flash if needed, and redirect to
labor_pathin all cases. Does that help?If in case of error you would need to redirect to something else, do something like:
If conditions are not mutually exclusive, i would write it like this:
I am not entirely sure if the
else nilis explicitly needed. Does this help?