Or maybe you can extract an method and do like this:

```ruby
def set_locale
  if params[:locale].present?
    set_i18n_locale(params[:locale])
  else
    set_i18n_locale(extract_locale_from_header || I18n.default_locale)
    redirect_to :root
  end
end

def set_i18n_locale(locale)
  I18n.locale = locale
  Rails.application.routes.default_url_options[:locale] = I18n.locale
end
```