Doublespeed Doublespeed - 1 month ago 6
Ruby Question

Not sure what this ruby method does

The below method is some code I inherited and it's supposed to remove parameters from a url but it's breaking with the following error:


ArgumentError: the input of URI.decode_www_form must be ASCII only
string
/home/fatman/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/uri/common.rb:969:in
`decode_www_form'


def self.removeUnnecessaryGetParams(url, removeParams = ["s"], whiteListParams = nil)
uri = Addressable::URI.parse(url)

#Get rid of UTM parameters & S parameters
if(uri.query != nil)

if(whiteListParams != nil)
cleanKeyVals = URI.decode_www_form(uri.query).reject{|k, _| !whiteListParams.include?(k)}
else
cleanKeyVals = URI.decode_www_form(uri.query).reject{|k, _| k.start_with?("utm_") or removeParams.include?(k)}
end

uri.query = URI.encode_www_form(cleanKeyVals)
end

return uri.to_s.split("#")[0].chomp("?")
end


1). My Question is, how exactly is this method working? Not sure what the lines are doing that assign to
cleankeyVals
(my ruby knowledge shortcomings).

2). How to fix this ASCII only string issue?

Answer
  1. uri.query appears to be a Ruby Hash object, #reject will reject entries in the object that meet the predicate described within the block. The first sieve removes keys not in the whitelist, the second rejects based on keys that start with utm_ or keys that are within removeParams.
  2. Simply do url.gsub!(/\P{ASCII}/, '') on the line immediately following the function definition. This regex will strip out non ASCII characters for you. (As an aside #gsub! modifies the original while #gsub returns a copy, this is a common Ruby convention that you will see as you start to explore the language more)