Delete trailing "?" from line

I have this url:

http://localhost:3000/blog/posts?locale=en 

Do I have an assistant to remove ?locale=en url:

 def url_without_locale_params(url) uri = URI url params = Rack::Utils.parse_query uri.query params.delete 'locale' uri.query = params.to_param uri.to_s end 

With this helper, I get this url http://localhost:3000/blog/posts? . I would like to delete the final ? .

The result should be http://localhost:3000/blog/posts .

+7
source share
3 answers

The answers still concern the line itself. What you are actually doing says that it has the parameters "" . If you do this nil , if params.to_param == "" you will not have this problem.

 def url_without_locale_params(url) uri = URI url params = Rack::Utils.parse_query uri.query params.delete 'locale' uri.query = params.to_param.blank? ? nil : params.to_param uri.to_s end 

something like this should do the trick. The reason for this is that even with an empty string, the URI assumes something is being added, so does it put the initial one ? in.

+3
source

Use # gsub :

 uri = "http://localhost:3000/blog/posts?locale=en" uri.gsub(/\?.*/, '') #=> "http://localhost:3000/blog/posts" 
+9
source

String#chomp is an opportunity.

 1.9.3p392 :002 > "foobar?".chomp("?") => "foobar" 

Final method will be

 def url_without_locale_params(url) uri = URI url params = Rack::Utils.parse_query uri.query params.delete 'locale' uri.query = params.to_param uri.to_s.chomp("?") end 
+8
source

All Articles