Avoid dropping slashes in URL helpers (especially when called using .send () in url_helpers)

Perhaps the name of this question is cryptic, but the problem is real, I just updated the application from Rails 3 to 4 and ran into the following problem (on Ruby 2.0 and 2.1):

I have a method that calls several URL helpers in a loop using send (), for example:

class Sitemap include Rails.application.routes.url_helpers #... # regions = [:city, :county, :zip] regions.each do |region| url_params = ... # [name, additional_id] send("#{region}_url", url_params) end 

Rails 3 above lists URLs like http://example.com/cities/atlanta/2

In Rails 4, I get http://example.com/cities/atlanta%2f2

slash gets CGI, I don't want this. I use it to generate a sitemap XML file for my site and it seems to work even if the forward slash is escaped but looks ugly and I don’t know if it will work correctly for all bots or clients.

UPDATE: after some debugging, I found that CGI escaping happens somewhere in ActionDispatch :: Journey :: Visitors :: Formatter

 Router::Utils.escape_segment() # method call somewhere in ActionDispatch::Journey::Visitors::Formatter # during Visitors::Formatter.new(path_options).accept(path.spec) # in @set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE) # in a call to ActionDispatch::Routing::RouteSet::Generator#generate 
0
source share
1 answer

I was able to fix the problem with a slash sketch when creating the url, here is the change:

 # from: send(region_url, url_params) # to: send(region_url, { id: url_params[0], market_id: url_params[1]}) # sometimes url_params is a one element array 

The key is to provide a hash of parameters with explicitly assigned keys and values.

I use the method of sending a dynamic call (xxx_url) from the url_helpers module, which is included in my model. The url_params array looks like ['some-slug', 12]

+1
source

Source: https://habr.com/ru/post/973087/


All Articles