<commit_before># Make redirects for SEO needs
class SeoAssist
  def initialize(app)
    @app = app
  end

  def call(env)
    request = Rack::Request.new(env)
    params = request.params
    taxon_id = params['taxon']
    if !taxon_id.blank? && !taxon_id.is_a?(Hash) && taxon = Taxon.find(taxon_id)
      params.delete('taxon')
      query = build_query(params)

      #ensures no trailing / for taxon urls
      #TODO ensure that permalink is never stored with a trailing slash
      permalink = taxon.permalink[0...-1]

      new_location = "/t/#{permalink}"
      new_location += '?' + query unless query.blank?
      return [301, { 'Location'=> new_location }, []]
    elsif env["PATH_INFO"] =~ /^\/(t|products)(\/\S+)?\/$/
      #ensures no trailing / for taxon and product urls
      query = build_query(params)
      new_location = env["PATH_INFO"][0...-1]
      new_location += '?' + query unless query.blank?
      return [301, { 'Location'=> new_location }, []]
    end
    @app.call(env)
  end

  private

  def build_query(params)
    params.map { |k, v|
      if v.class == Array
        build_query(v.map { |x| ["#{k}[]", x] })
      else
        k + "=" + Rack::Utils.escape(v)
      end
    }.join("&")
  end

end
<commit_msg>refactor existing code and make it more DRY<commit_after># Make redirects for SEO needs
class SeoAssist
  def initialize(app)
    @app = app
  end

  def call(env)
    request = Rack::Request.new(env)
    params = request.params
    taxon_id = params['taxon']
    if !taxon_id.blank? && !taxon_id.is_a?(Hash) && taxon = Taxon.find(taxon_id)
      params.delete('taxon')

      #ensures no trailing / for taxon urls
      #TODO ensure that permalink is never stored with a trailing slash
      permalink = taxon.permalink[0...-1]
      return build_response(params, "/t/#{permalink}" )

    elsif env["PATH_INFO"] =~ /^\/(t|products)(\/\S+)?\/$/
      #ensures no trailing / for taxon and product urls
      return build_response(params, env["PATH_INFO"][0...-1])
    end
    @app.call(env)
  end

  private

  def build_response(params, location)
    query = build_query(params)
    new_location = location + '?' + query unless query.blank?
    [301, { 'Location'=> new_location }, []]
  end

  def build_query(params)
    params.map { |k, v|
      if v.class == Array
        build_query(v.map { |x| ["#{k}[]", x] })
      else
        k + "=" + Rack::Utils.escape(v)
      end
    }.join("&")
  end

end

{'fraction_non_alphanumeric': 0.15196078431372548, 'fraction_numerical': 0.006944444444444444, 'mean_word_length': 2.6606875934230194, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7449236', 'n_tokens_mistral': 874, 'n_tokens_neox': 852, 'n_words': 211}